• Stars
    star
    124
  • Rank 278,977 (Top 6 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created over 8 years ago
  • Updated 27 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple go wrapper for the OVH API

go-ovh

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

GoDoc Build Status Coverage Status Go Report Card

package main

import (
	"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 definition
type PartialMe struct {
	Firstname string `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.
func main() {
	var me PartialMe

	client, _ := 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 your import and run go get:

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

Configuration

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

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

This wrapper will first look for direct instanciation parameters then OVH_ENDPOINT, OVH_APPLICATION_KEY, OVH_APPLICATION_SECRET and OVH_CONSUMER_KEY environment variables. If either of these parameter is not provided, it will look for a configuration file of the form:

[default]
; general configuration: default endpoint
endpoint=ovh-eu

[ovh-eu]
; configuration specific to 'ovh-eu' endpoint
application_key=my_app_key
application_secret=my_application_secret
consumer_key=my_consumer_key

Depending on the API you want to use, you may set the endpoint 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 specific project or user.

Register your app

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

Hence, to use the API, you must first register your application and then ask your user 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 is 24h. He may also revoke an authorization at any time. Hence, your application should be prepared to receive 403 HTTP errors and prompt the user to re-authenticated.

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

Use the API on behalf of a user

Visit https://eu.api.ovh.com/createApp and create your app You'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 the GET 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 and application secret. You can add the consumer key once generated. For alternate configuration method, please see the configuration section.

[ovh-eu]
application_key=my_app_key
application_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 main

import (
	"fmt"

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

func main() {
	// Create a client using credentials from config files or environment variables
	client, err := ovh.NewEndpointClient("ovh-eu")
	if err != nil {
		fmt.Printf("Error: %q\n", err)
		return
	}
	ckReq := client.NewCkRequest()

	// Allow GET method on /me
	ckReq.AddRules(ovh.ReadOnly, "/me")

	// Allow GET method on /xdsl and all its sub routes
	ckReq.AddRecursiveRules(ovh.ReadOnly, "/xdsl")

	// Run the request
	response, err := ckReq.Do()
	if err != nil {
		fmt.Printf("Error: %q\n", err)
		return
	}

	// Print the validation URL and the Consumer key
	fmt.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 will typically want to do this when writing automation scripts for a single projects.

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

ovh.conf should look like:

[ovh-eu]
application_key=my_app_key
application_secret=my_application_secret
consumer_key=my_consumer_key

Use the lib

These examples assume valid credentials are available in the configuration.

GET

package main

import (
	"fmt"

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

func main() {
	client, err := ovh.NewEndpointClient("ovh-eu")
	if err != nil {
		fmt.Printf("Error: %q\n", err)
		return
	}

	// Get all the xdsl services
	xdslServices := []string{}
	if err := client.Get("/xdsl/", &xdslServices); err != nil {
		fmt.Printf("Error: %q\n", err)
		return
	}

	// xdslAccess represents a xdsl access returned by the API
	type xdslAccess struct {
		Name   string `json:"accessName"`
		Status string `json:"status"`
		Pairs  int	`json:"pairsNumber"`
		// Insert the other properties here
	}

	// Get the details of each service
	for i, serviceName := range xdslServices {
		access := xdslAccess{}
		url := "/xdsl/" + serviceName

		if err := client.Get(url, &access); err != nil {
			fmt.Printf("Error: %q\n", err)
			return
		}
		fmt.Printf("#%d : %+v\n", i+1, access)
	}
}

PUT

package main

import (
	"fmt"

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

func main() {
	client, err := ovh.NewEndpointClient("ovh-eu")
	if err != nil {
		fmt.Printf("Error: %q\n", err)
		return
	}

	// Params
	type AccessPutParams struct {
		Description string `json:"description"`
	}

	// Update the description of the service
	params := &AccessPutParams{Description: "My awesome access"}
	if err := 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 the opportunity to aim for two API versions. For the European API, for example:

Calling client.Get, you can target the API version you want:

client, _ := ovh.NewEndpointClient("ovh-eu")

// Call to https://eu.api.ovh.com/v1/xdsl/xdsl-yourservice
client.Get("/v1/xdsl/xdsl-yourservice", nil)

// Call to https://eu.api.ovh.com/v2/xdsl/xdsl-yourservice
client.Get("/v2/xdsl/xdsl-yourservice", nil)

// Legacy call to https://eu.api.ovh.com/1.0/xdsl/xdsl-yourservice
client.Get("/xdsl/xdsl-yourservice", nil)

API Documentation

Create a client

  • Use ovh.NewClient() to have full controll over ther authentication
  • Use ovh.NewEndpointClient() to create a client for a specific API and use credentials from config files or environment
  • Use ovh.NewDefaultClient() to create a client unsing endpoint and credentials from config files or environment

Query

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

Each helper accepts a method and resType argument. method is the full URI, including the query string, and resType is a reference to an object in which the json response will be unserialized.

Additionally, Post, Put and their UnAuth variant accept a reqBody which is a reference to a json serializable object or nil.

Alternatively, you may directly use the low level CallAPI method.

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

Or, for unauthenticated requests:

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

Request consumer keys

Consumer keys may be restricted to a subset of the API. This allows to delegate the API to manage only 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 pattern is a plain API method and may contain the '*' wilcard to match "anything". Just like glob on a Unix machine.

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

example: Grant on all /sms and identity

client, err := ovh.NewEndpointClient("ovh-eu")
if err == 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 a CkRequest:

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 PATH
req.AddRules(ovh.ReadOnly, "/PATH")

// This will generate all patterns for PATH for all HTTP verbs
req.AddRules(ovh.ReadWrite, "/PATH")

// This will generate all patterns for PATH for all HTTP verbs, except DELETE
req.AddRules(ovh.ReadWriteSafe, "/PATH")

Request access on path and all sub-path:

// This will generate all patterns for GET PATH
req.AddRecursiveRules(ovh.ReadOnly, "/PATH")

// This will generate all patterns for PATH for all HTTP verbs
req.AddRecursiveRules(ovh.ReadWrite, "/PATH")

// This will generate all patterns for PATH for all HTTP verbs, except DELETE
req.AddRecusriveRules(ovh.ReadWriteSafe, "/PATH")

Create key:

pendingCk, err := req.Do()

This will initiate the consumer key validation process and return both a consumer key and a validation URL. The consumer key is automatically added to the client which was used to create the request. It may be used as soon as the user has authenticated the request on the validation 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/ovh
cd $GOPATH/src/github.com/ovh/go-ovh/ovh
go get

You've developed a new cool feature ? Fixed an annoying bug ? We'd be happy to hear from you ! See CONTRIBUTING.md for more informations

Run the tests

Simply run go test. Since we all love quality, please note that we do not accept contributions lowering coverage.

# Run all tests, with coverage
go test -cover

# Validate code quality
golint ./...
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

More Repositories

1

cds

Enterprise-Grade Continuous Delivery & DevOps Automation Open Source Platform
Go
4,440
star
2

the-bastion

Authentication, authorization, traceability and auditability for SSH accesses.
Perl
1,429
star
3

utask

Β΅Task is an automation engine that models and executes business processes declared in yaml. βœοΈπŸ“‹
Go
1,100
star
4

venom

🐍 Manage and run your integration tests with efficiency - Venom run executors (script, HTTP Request, web, imap, etc... ) and assertions
Go
974
star
5

debian-cis

PCI-DSS compliant Debian 10/11/12 hardening
Shell
667
star
6

celery-director

Simple and rapid framework to build workflows with Celery
Python
512
star
7

svfs

The Swift Virtual File System
Go
373
star
8

php-ovh

Lightweight PHP wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your PHP applications.
PHP
287
star
9

python-ovh

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing.
Python
266
star
10

docs

Official repository containing all docs & guides of OVH Group
HTML
214
star
11

manager

OVHcloud Control Panel
JavaScript
203
star
12

overthebox

OverTheBox - Aggregate and encrypt your multiple internet connections.
Shell
194
star
13

public-cloud-roadmap

Agile roadmap for OVHcloud Public Cloud services. Discover the features our product teams are working on, comment and influence our backlog.
183
star
14

terraform-provider-ovh

Terraform OVH provider
Go
178
star
15

metronome

Metronome is a distributed and fault-tolerant event scheduler
Go
135
star
16

node-ovh

Node.js wrapper for the OVH APIs
JavaScript
125
star
17

ai-training-examples

Jupyter Notebook
121
star
18

symmecrypt

Golang symmetric encryption library
Go
108
star
19

overthebox-feeds

OverTheBox - LEDE/OpenWrt feed
HTML
106
star
20

ovh-ttyrec

Enhanced (but compatible) version of the classic ttyrec
C
105
star
21

overthebox-openwrt

OverTheBox - OpenWrt fork
C
98
star
22

sv2chisel

(System)Verilog to Chisel translator
Scala
97
star
23

celery-dyrygent

Celery extension which allows to orchestrate 100/1000/10000 tasks combined into a complex workflow
Python
94
star
24

tat

Tat Engine - Text And Tags
Go
89
star
25

beamium

Prometheus to Warp10 metrics forwarder
Rust
84
star
26

ip-reputation-monitoring

Monitor the reputation of your IP ranges
Python
82
star
27

depc

QoS Measurement & Dependency Graph Platform
Python
80
star
28

configstore

Golang configuration management library
Go
62
star
29

erlenmeyer

Erlenmeyer is a proxy used to parse common Open Source TimeSeries DataBase query endpoints like OpenTSDB, Prometheus/PromQL, InfluxQL or Graphite. Parsed queries are translated into WarpScript to produce native Warp 10 queries.
Go
60
star
30

tsl

TSL is a HTTP proxy which generate WarpScript or a PromQl script based on a TSL query.
Go
56
star
31

noderig

Export OS stats as Sensision Metrics
Go
55
star
32

ovh-ui-kit

OVHcloud UI Kit - Master UI Framework
JavaScript
53
star
33

terraform-ovh-commons

This repo contains commons resources to interact with OVH Public Cloud using Terraform.
HTML
53
star
34

php-ovh-sms

PHP for ovh sms API
PHP
49
star
35

ovh-cli

OVH Command Line Interface
Python
41
star
36

infrastructure-roadmap

34
star
37

summit2016-RankingPredict

Deprecated, No more maintained - Deprecated, no longer maintained
R
34
star
38

ovh-warp10-datasource

Grafana datasource for Warp10 platform
TypeScript
33
star
39

the-bastion-ansible-wrapper

Using Ansible through The Bastion
Python
30
star
40

csharp-ovh

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing
C#
27
star
41

order-cart-examples

Example code snippets demonstrating how to use new order with cart on api.ovh.com
PHP
25
star
42

ldp-tail

OVH Logs Data Platform - Tail CLI tooling
Go
24
star
43

haproxy-exporter

Export HAProxy stats as Sensision Metrics
Go
21
star
44

fossil

Fossil is a proxy for securing unencrypted Graphite metrics collection
Go
20
star
45

java-ovh

Thin wrapper around OVH's APIs. Handles all the hard work including credential creation and requests signing
Java
19
star
46

tatwebui

Tat Web UI - Text And Tags
JavaScript
19
star
47

terraform-ovh-publiccloud-network

HCL
19
star
48

python-apispec-fromfile

APISpec plugin to import OpenAPI specifications from a file
Python
18
star
49

design-system

A collection of assets, guidelines and UI components for building consistent user experiences across OVHcloud products.
TypeScript
18
star
50

public-cloud-examples

Jupyter Notebook
18
star
51

cerberus-ux

HTML
15
star
52

lxd-puppet-module

Ruby
14
star
53

website-evidence-collector-batch

A tool to launch website-evidence-collector on several URLs or Sitemaps and generate a full report.
JavaScript
14
star
54

osarchiver

OpenStack databases archiver
Python
14
star
55

jerem

Jerem is a golang bot that scrap JIRA project to extract Metrics. Those Metrics can then be send to a Warp 10 Backend.
Go
14
star
56

cerberus-core

Cerberus is a toolkit to receive, parse, process and automate abuse reports handling received by ISP or hosting providers.
Python
14
star
57

ovh-ui-kit-bs

A bootstrap theme for the OVH managers, based on ovh-ui-kit
Less
13
star
58

prescience-client

Desktop python client for using OVH Prescience service
Jupyter Notebook
13
star
59

gulp-drupal-stack

OVH Gulp tasks for Drupal themes and modules
JavaScript
12
star
60

public-cloud-databases-examples

OVHcloud Public Cloud Databases Training examples
HCL
12
star
61

distronaut

Find distribution installers all across the web !
Go
12
star
62

serving-runtime

Exposes a serialized machine learning model through a HTTP API.
Java
12
star
63

metronome-ui

User interface for Metronome
JavaScript
11
star
64

private-cloud-roadmap

11
star
65

swift-ovh

This Swift package is a lightweight wrapper for OVH APIs. That's the easiest way to use OVH.com APIs in your Swift applications. Apple platforms supported: iOS, OSX, tvOS, watchOS.
Swift
11
star
66

rtm

RTM (OVH Real Time Monitoring)
Perl
11
star
67

pulumi-ovh

Pulumi provider for OVHcloud
Python
11
star
68

telephony-example-cti-dashboard

Shows signaling events provided by OVH France telephony services CTI
CSS
11
star
69

drucker

Drucker is a lightweight Drupal Developer Environment.
Shell
10
star
70

phishing-mitigation

Tilera-based phishing mitigation layer
JavaScript
10
star
71

lhasa

List and map micro-services-based information system and observe how they interact. Track their activities, then gamify their continuous improvement.
Go
10
star
72

overthebox-lede

OverTheBox - LEDE fork
C
8
star
73

owstats-ui

JavaScript
8
star
74

python-logging-gelf

A python logging bundle to send logs using GELF
Python
8
star
75

webpaas-cli

PHP
7
star
76

vbridge

X11 cloud desktop software
C
7
star
77

djehouty

Djehouty intends to be a set of logging formatters and handlers to easily send log entries.
Python
7
star
78

crystal-ovh

Lightweight Crystal wrapper around OVH's APIs.
Crystal
7
star
79

ovhdata-cli

Rust
7
star
80

python-warp10client

Python
7
star
81

data-processing-spark-submit

Spark CLI wrapper to run your jobs on OVHcloud Data Processing
Go
7
star
82

interpretability-engine

Interpret Machine Learning black-box models deployed on Serving Engine
Python
6
star
83

terraform-provider-mimirtool

Terraform provider for Grafana Mimir
Go
6
star
84

webhosting-ssh-bashrc

Shell
6
star
85

tat-contrib

Go
6
star
86

puppet-thebastion

Puppet module for Thebastion management.
Ruby
6
star
87

public-cloud-databases-operator

This operator allow you to automaticaly authorize your Kubernetes cluster IP on your OVHcloud cloud databases service.
Go
6
star
88

docs-developer-env

Easy to deploy developer environment, for writing/testing guides & documentations for docs.ovh.com
Shell
6
star
89

docs-rendering

[DEPRECATED] Official rendering engine for static generation of OVH Docs platform
HTML
6
star
90

terraform-ovh-publiccloud-docker-swarm

HCL
5
star
91

terraform-ovh-publiccloud-spark

HCL
5
star
92

summit2016-webhosting-example-rondcoin

PHP
5
star
93

collectd-write-warp10

Python
5
star
94

fiowebviewer

Python
5
star
95

yubico-piv-checker

Go
4
star
96

puppet-mimir

Ruby
4
star
97

pingdom-to-graphite

A tool for copying metrics from Pingdom to Graphite.
JavaScript
4
star
98

ovh-winston-ldp

A graylog2 TCP/TLS transport for winston library
JavaScript
4
star
99

bringyourownlinux

Shell
4
star
100

.github

Community health files for the @ovh organization
3
star