Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/go-ovhPublic

Simple go wrapper for the OVH API

License

NotificationsYou must be signed in to change notification settings

ovh/go-ovh

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Lightweight Go wrapper around OVHcloud's APIs. Handles all the hard work including credential creation and requests signing.

GoDocBuild StatusCoverage StatusGo Report Card

package mainimport ("fmt""github.com/ovh/go-ovh/ovh")// PartialMe holds the first name of the currently logged-in user.// Visit https://api.ovh.com/console/#/me#GET for the full definitiontypePartialMestruct {Firstnamestring`json:"firstname"`}// Instantiate an OVH client and get the firstname of the currently logged-in user.// Visit https://api.ovh.com/createToken/index.cgi?GET=/me to get your credentials.funcmain() {varmePartialMeclient,_:=ovh.NewClient("ovh-eu",YOUR_APPLICATION_KEY,YOUR_APPLICATION_SECRET,YOUR_CONSUMER_KEY,)client.Get("/me",&me)fmt.Printf("Welcome %s!\n",me.Firstname)}

Installation

The Golang wrapper has been tested with Golang 1.18+. It may worker with older versions although it has not been tested.

To use it, just include it to yourimport and rungo get:

import (..."github.com/ovh/go-ovh/ovh")

Configuration

The straightforward way to use OVHcloud's API keys is to embed them directly in theapplication code. While this is very convenient, it lacks of elegance andflexibility.

Alternatively it is suggested to use configuration files or environmentvariables so that the same code may run seamlessly in multiple environments.Production and development for instance.

go-ovh supports two forms of authentication:

  • OAuth2, using scopped service accounts, and compatible with OVHcloud IAM
  • application key & application secret & consumer key

OAuth2

First, you need to generate a pair of validclient_id andclient_secret: youcan proceed byfollowing this documentation

Once you have retrieved yourclient_id andclient_secret, you can create and edita configuration file that will be used bygo-ovh.

[default]; general configuration: default endpointendpoint=ovh-eu[ovh-eu]; configuration specific to 'ovh-eu' endpointclient_id=my_client_idclient_secret=my_client_secret

The client will successively attempt to locate this configuration file in

  1. Current working directory:./ovh.conf
  2. Current user's home directory:~/.ovh.conf
  3. System wide configuration:/etc/ovh.conf

Depending on the API you want to use, you may set theendpoint to:

  • ovh-eu for OVHcloud Europe API
  • ovh-us for OVHcloud US API
  • ovh-ca for OVHcloud Canada API

This lookup mechanism makes it easy to overload credentials for a specificproject or user.

Access Token

This authentication method is useful when short-lived credentials are necessary.E.g. oauth2pluginfor HashiCorp Vault can request an access token that would be used by OVHcloudterraform provider. Although this token, requested via data-source, would end upstored in the Terraform state file, that would pose less risk since the tokenvalidity would last for only 1 hour.

Other applications are of course also possible.

In order to use the access token with this wrapper either useovh.NewAccessTokenClient to create the client, or pass the token viaOVH_ACCESS_TOKEN environment variable toovh.NewDefaultClient.

Application Key/Application Secret

If you have completed successfully theOAuth2 part, you can continue tothe Use the Lib part.

This section will cover the legacy authentication method using application key andapplication secret.This wrapper will first look for direct instanciation parameters thenOVH_ENDPOINT,OVH_APPLICATION_KEY,OVH_APPLICATION_SECRET andOVH_CONSUMER_KEY environment variables. If either of these parameter is notprovided, it will look for a configuration file of the form:

[default]; general configuration: default endpointendpoint=ovh-eu[ovh-eu]; configuration specific to 'ovh-eu' endpointapplication_key=my_app_keyapplication_secret=my_application_secretconsumer_key=my_consumer_key

Depending on the API you want to use, you may set theendpoint to:

  • ovh-eu for OVHcloud Europe API
  • ovh-us for OVHcloud US API
  • ovh-ca for OVHcloud Canada API
  • soyoustart-eu for So you Start Europe API
  • soyoustart-ca for So you Start Canada API
  • kimsufi-eu for Kimsufi Europe API
  • kimsufi-ca for Kimsufi Canada API
  • Or any arbitrary URL to use in a test for example

The client will successively attempt to locate this configuration file in

  1. Current working directory:./ovh.conf
  2. Current user's home directory~/.ovh.conf
  3. System wide configuration/etc/ovh.conf

This lookup mechanism makes it easy to overload credentials for a specificproject or user.

Register your app

OVHcloud's API, like most modern APIs is designed to authenticate both an application anda user, without requiring the user to provide a password. Your application will beidentified by its "application secret" and "application key" tokens.

Hence, to use the API, you must first register your application and then ask youruser to authenticate on a specific URL. Once authenticated, you'll have a valid"consumer key" which will grant your application on specific APIs.

The user may choose the validity period of his authorization. The default period is24h. He may also revoke an authorization at any time. Hence, your application shouldbe prepared to receive 403 HTTP errors and prompt the user to re-authenticate.

This process is detailed in the following section. Alternatively, you may only needto build an application for a single user. In this case you may generate allcredentials at once. See below.

Use the API on behalf of a user

Visithttps://eu.api.ovh.com/createApp and create your appYou'll get an application key and an application secret. To use the API you'll need a consumer key.

The consumer key has two types of restriction:

  • path: eg. only theGET method on/me
  • time: eg. expire in 1 day

Then, get a consumer key. Here's an example on how to generate one.

First, create a 'ovh.conf' file in the current directory with the application key andapplication secret. You can add the consumer key once generated. For alternateconfiguration method, please see theconfiguration section.

[ovh-eu]application_key=my_app_keyapplication_secret=my_application_secret; consumer_key=my_consumer_key

Then, you may use a program like this example to create a consumer key for the application:

package mainimport ("fmt""github.com/ovh/go-ovh/ovh")funcmain() {// Create a client using credentials from config files or environment variablesclient,err:=ovh.NewEndpointClient("ovh-eu")iferr!=nil {fmt.Printf("Error: %q\n",err)return}ckReq:=client.NewCkRequest()// Allow GET method on /meckReq.AddRules(ovh.ReadOnly,"/me")// Allow GET method on /xdsl and all its sub routesckReq.AddRecursiveRules(ovh.ReadOnly,"/xdsl")// Run the requestresponse,err:=ckReq.Do()iferr!=nil {fmt.Printf("Error: %q\n",err)return}// Print the validation URL and the Consumer keyfmt.Printf("Generated consumer key: %s\n",response.ConsumerKey)fmt.Printf("Please visit %s to validate it\n",response.ValidationURL)}
Use the API for a single user

Alternatively, you may generate all creadentials at once, including the consumer key. You willtypically want to do this when writing automation scripts for a single projects.

If this case, you may want to directly go tohttps://eu.api.ovh.com/createToken/ to generatethe 3 tokens at once. Make sure to save them in one of the 'ovh.conf' configuration file.Please see theconfiguration section.

ovh.conf should look like:

[ovh-eu]application_key=my_app_keyapplication_secret=my_application_secretconsumer_key=my_consumer_key

Use the lib

These examples assume valid credentials are available in theconfiguration.

GET

package mainimport ("fmt""github.com/ovh/go-ovh/ovh")funcmain() {client,err:=ovh.NewEndpointClient("ovh-eu")iferr!=nil {fmt.Printf("Error: %q\n",err)return}// Get all the xdsl servicesxdslServices:= []string{}iferr:=client.Get("/xdsl/",&xdslServices);err!=nil {fmt.Printf("Error: %q\n",err)return}// xdslAccess represents a xdsl access returned by the APItypexdslAccessstruct {Namestring`json:"accessName"`Statusstring`json:"status"`Pairsint`json:"pairsNumber"`// Insert the other properties here}// Get the details of each servicefori,serviceName:=rangexdslServices {access:=xdslAccess{}url:="/xdsl/"+serviceNameiferr:=client.Get(url,&access);err!=nil {fmt.Printf("Error: %q\n",err)return}fmt.Printf("#%d : %+v\n",i+1,access)}}

PUT

package mainimport ("fmt""github.com/ovh/go-ovh/ovh")funcmain() {client,err:=ovh.NewEndpointClient("ovh-eu")iferr!=nil {fmt.Printf("Error: %q\n",err)return}// ParamstypeAccessPutParamsstruct {Descriptionstring`json:"description"`}// Update the description of the serviceparams:=&AccessPutParams{Description:"My awesome access"}iferr:=client.Put("/xdsl/xdsl-yourservice",params,nil);err!=nil {fmt.Printf("Error: %q\n",err)return}fmt.Println("Description updated")}

Use v1 and v2 API versions

When using OVHcloud APIs (not So you Start or Kimsufi ones), you are given theopportunity to aim for two API versions. For the European API, for example:

Callingclient.Get, you can target the API version you want:

client,_:=ovh.NewEndpointClient("ovh-eu")// Call to https://eu.api.ovh.com/v1/xdsl/xdsl-yourserviceclient.Get("/v1/xdsl/xdsl-yourservice",nil)// Call to https://eu.api.ovh.com/v2/xdsl/xdsl-yourserviceclient.Get("/v2/xdsl/xdsl-yourservice",nil)// Legacy call to https://eu.api.ovh.com/1.0/xdsl/xdsl-yourserviceclient.Get("/xdsl/xdsl-yourservice",nil)

API Documentation

Create a client

  • Useovh.NewDefaultClient() to create a client using endpoint and credentials from config files or environment
  • Useovh.NewEndpointClient() to create a client for a specific API and use credentials from config files or environment
  • Useovh.NewOAuth2Client() to have full control over their authentication, using OAuth2 authentication method
  • Useovh.NewAccessTokenClient() to have full control over their authentication, using token that was previously issued by auth/oauth2/token endpoint
  • Useovh.NewClient() to have full control over their authentication, using legacy authentication method

Query

Each HTTP verb has its own Client method. Some API methods supports unauthenticated calls. Forthese methods, you may want to use the*UnAuth variant of the Client which will bypassrequest signature.

Each helper accepts amethod andresType argument.method is the full URI, includingthe query string, andresType is a reference to an object in which the json response willbe unserialized.

Additionally,Post,Put and theirUnAuth variant accept a reqBody which is areference to a json serializable object or nil.

Alternatively, you may directly use the low levelCallAPI method.

  • Useclient.Get() for GET requests
  • Useclient.Post() for POST requests
  • Useclient.Put() for PUT requests
  • Useclient.Delete() for DELETE requests

Or, for unauthenticated requests:

  • Useclient.GetUnAuth() for GET requests
  • Useclient.PostUnAuth() for POST requests
  • Useclient.PutUnAuth() for PUT requests
  • Useclient.DeleteUnAuth() for DELETE requests

Request consumer keys

[Only valid for legacy authentication method]

Consumer keys may be restricted to a subset of the API. This allows to delegate the API to manageonly a specific server or domain name for example. This is called "scoping" a consumer key.

Rules are simple. They combine an HTTP verb (GET, POST, PUT or DELETE) with a pattern. A patternis a plain API method and may contain the '*' wilcard to match "anything". Just like glob on aUnix machine.

While this is simple and may be managed directly with the API as-is, this can be cumbersome to doand we recommend using theCkRequest helper. It basically manages the list of authorizationsfor you and the actual request.

example: Grant on all /sms and identity

client,err:=ovh.NewEndpointClient("ovh-eu")iferr==nil {// Do something}req:=client.NewCkRequest()req.AddRules(ovh.ReadOnly,"/me")req.AddRecursiveRulesRules(ovh.ReadWrite,"/sms")pendingCk,err:=req.Do()

This example will generate a request for:

  • GET /me
  • GET /sms
  • GET /sms/*
  • POST /sms
  • POST /sms/*
  • PUT /sms
  • PUT /sms/*
  • DELETE /sms
  • DELETE /sms/*

Which would be tedious to do by hand...

Create aCkRequest:

req:=client.NewCkRequest()

Request access on a specific path and method (advanced):

// Use this method for fine-grain access control. In most case, you'll// want to use the methods below.req.AddRule("VERB","PATTERN")

Request access on specific path:

// This will generate all patterns for GET PATHreq.AddRules(ovh.ReadOnly,"/PATH")// This will generate all patterns for PATH for all HTTP verbsreq.AddRules(ovh.ReadWrite,"/PATH")// This will generate all patterns for PATH for all HTTP verbs, except DELETEreq.AddRules(ovh.ReadWriteSafe,"/PATH")

Request access on path and all sub-path:

// This will generate all patterns for GET PATHreq.AddRecursiveRules(ovh.ReadOnly,"/PATH")// This will generate all patterns for PATH for all HTTP verbsreq.AddRecursiveRules(ovh.ReadWrite,"/PATH")// This will generate all patterns for PATH for all HTTP verbs, except DELETEreq.AddRecusriveRules(ovh.ReadWriteSafe,"/PATH")

Create key:

pendingCk,err:=req.Do()

This will initiate the consumer key validation process and return both a consumer key anda validation URL. The consumer key is automatically added to the client which was used tocreate the request. It may be used as soon as the user has authenticated the request on thevalidation URL.

pendingCk contains 3 fields:

  • ValidationURL the URL the user needs to visit to activate the consumer key
  • ConsumerKey the new consumer key. It won't be active until validation
  • State the consumer key state. Always "pendingValidation" at this stage

Hacking

This wrapper uses standard Go tools, so you should feel at home with it.Here is a quick outline of what it may look like.

Get the sources

go get github.com/ovh/go-ovh/ovhcd $GOPATH/src/github.com/ovh/go-ovh/ovhgo get

You've developed a new cool feature ? Fixed an annoying bug ? We'd be happyto hear from you ! SeeCONTRIBUTING.mdfor more informations

Run the tests

Simply rungo test. Since we all love quality, pleasenote that we do not accept contributions lowering coverage.

# Run all tests, with coveragego test -cover# Validate code qualitygolint ./...go vet ./...

Supported APIs

OVHcloud Europe

OVHcloud US

OVHcloud Canada

So you Start Europe

So you Start Canada

Kimsufi Europe

Kimsufi Canada

License

3-Clause BSD


[8]ページ先頭

©2009-2025 Movatter.jp