Categorygithub.com/flowswiss/gophercloud/v2
modulepackage
2.2.1
Repository: https://github.com/flowswiss/gophercloud.git
Documentation: pkg.go.dev

# README

Gophercloud: an OpenStack SDK for Go

Coverage Status

Reference documentation

Gophercloud is a Go SDK for OpenStack.

Join us on kubernetes slack, on #gophercloud. Visit slack.k8s.io for an invitation.

Note This branch contains the current stable branch of Gophercloud: v2. The legacy stable version can be found in the v1 branch.

How to install

Reference a Gophercloud package in your code:

import "github.com/gophercloud/gophercloud/v2"

Then update your go.mod:

go mod tidy

Getting started

Credentials

Because you'll be hitting an API, you will need to retrieve your OpenStack credentials and either store them in a clouds.yaml file, as environment variables, or in your local Go files. The first method is recommended because it decouples credential information from source code, allowing you to push the latter to your version control system without any security risk.

You will need to retrieve the following:

  • A valid Keystone identity URL
  • Credentials. These can be a username/password combo, a set of Application Credentials, a pre-generated token, or any other supported authentication mechanism.

For users who have the OpenStack dashboard installed, there's a shortcut. If you visit the project/api_access path in Horizon and click on the "Download OpenStack RC File" button at the top right hand corner, you can download either a clouds.yaml file or an openrc bash file that exports all of your access details to environment variables. To use the clouds.yaml file, place it at ~/.config/openstack/clouds.yaml. To use the openrc file, run source openrc and you will be prompted for your password.

Gophercloud authentication

Gophercloud authentication is organized into two layered abstractions:

  • ProviderClient holds the authentication token and can be used to build a ServiceClient.
  • ServiceClient specializes against one specific OpenStack module and can directly be used to make API calls.

A provider client is a top-level client that all of your OpenStack service clients derive from. The provider contains all of the authentication details that allow your Go code to access the API - such as the base URL and token ID.

One single Provider client can be used to build as many Service clients as needed.

With clouds.yaml

package main

import (
	"context"

	"github.com/gophercloud/gophercloud/v2/openstack"
	"github.com/gophercloud/gophercloud/v2/openstack/config"
	"github.com/gophercloud/gophercloud/v2/openstack/config/clouds"
)

func main() {
	ctx := context.Background()

	// Fetch coordinates from a `cloud.yaml` in the current directory, or
	// in the well-known config directories (different for each operating
	// system).
	authOptions, endpointOptions, tlsConfig, err := clouds.Parse()
	if err != nil {
		panic(err)
	}

	// Call Keystone to get an authentication token, and use it to
	// construct a ProviderClient. All functions hitting the OpenStack API
	// accept a `context.Context` to enable tracing and cancellation.
	providerClient, err := config.NewProviderClient(ctx, authOptions, config.WithTLSConfig(tlsConfig))
	if err != nil {
		panic(err)
	}

	// Use the ProviderClient and the endpoint options fetched from
	// `clouds.yaml` to build a service client: a compute client in this
	// case. Note that the contructor does not accept a `context.Context`:
	// no further call to the OpenStack API is needed at this stage.
	computeClient, err := openstack.NewComputeV2(providerClient, endpointOptions)
	if err != nil {
		panic(err)
	}

	// use the computeClient
}

With environment variables (openrc)

Gophercloud can parse the environment variables set by running source openrc:

package main

import (
	"context"
	"os"

	"github.com/gophercloud/gophercloud/v2"
	"github.com/gophercloud/gophercloud/v2/openstack"
)

func main() {
	ctx := context.Background()

	opts, err := openstack.AuthOptionsFromEnv()
	if err != nil {
		panic(err)
	}

	providerClient, err := openstack.AuthenticatedClient(ctx, opts)
	if err != nil {
		panic(err)
	}

	computeClient, err := openstack.NewComputeV2(providerClient, gophercloud.EndpointOpts{
		Region: os.Getenv("OS_REGION_NAME"),
	})
	if err != nil {
		panic(err)
	}

	// use the computeClient
}

Manually

You can also generate a "Provider" by passing in your credentials explicitly:

package main

import (
	"context"

	"github.com/gophercloud/gophercloud/v2"
	"github.com/gophercloud/gophercloud/v2/openstack"
)

func main() {
	ctx := context.Background()

	providerClient, err := openstack.AuthenticatedClient(ctx, gophercloud.AuthOptions{
		IdentityEndpoint: "https://openstack.example.com:5000/v2.0",
		Username:         "username",
		Password:         "password",
	})
	if err != nil {
		panic(err)
	}

	computeClient, err := openstack.NewComputeV2(providerClient, gophercloud.EndpointOpts{
		Region: "RegionName",
	})
	if err != nil {
		panic(err)
	}

	// use the computeClient
}

Provision a server

We can use the Compute service client generated above for any Compute API operation we want. In our case, we want to provision a new server. To do this, we invoke the Create method and pass in the flavor ID (hardware specification) and image ID (operating system) we're interested in:

import "github.com/gophercloud/gophercloud/v2/openstack/compute/v2/servers"

func main() {
    // [...]

    server, err := servers.Create(context.TODO(), computeClient, servers.CreateOpts{
        Name:      "My new server!",
        FlavorRef: "flavor_id",
        ImageRef:  "image_id",
    }).Extract()

    // [...]

The above code sample creates a new server with the parameters, and returns a servers.Server.

Supported Services

ServiceNameModule1.x2.x
BaremetalIronicopenstack/baremetal
Baremetal IntrospectionIronic Inspectoropenstack/baremetalintrospection
Block StorageCinderopenstack/blockstorage
ClusteringSenlinopenstack/clustering
ComputeNovaopenstack/compute
ContainerZunopenstack/container
Container InfrastructureMagnumopenstack/containerinfra
DatabaseTroveopenstack/db
DNSDesignateopenstack/dns
IdentityKeystoneopenstack/identity
ImageGlanceopenstack/image
Key ManagementBarbicanopenstack/keymanager
Load BalancingOctaviaopenstack/loadbalancer
MessagingZaqaropenstack/messaging
NetworkingNeutronopenstack/networking
Object StorageSwiftopenstack/objectstorage

Advanced Usage

Have a look at the FAQ for some tips on customizing the way Gophercloud works.

Backwards-Compatibility Guarantees

Gophercloud versioning follows semver.

Before v1.0.0, there were no guarantees. Starting with v1, there will be no breaking changes within a major release.

See the Release instructions.

Contributing

See the contributing guide.

Help and feedback

If you're struggling with something or have spotted a potential bug, feel free to submit an issue to our bug tracker.

# Packages

Package openstack contains resources for the individual OpenStack projects supported in Gophercloud.
Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs.
Package testhelper container methods that are useful for writing unit tests.
gophercloud.

# Functions

BuildHeaders is an internal function to be used by request methods in individual resource packages.
BuildQueryString is an internal function to be used by request methods in individual resource packages.
BuildRequestBody builds a map[string]interface from the given `struct`.
ExtractNextURL is an internal function useful for packages of collection resources that are paginated in a certain way.
IDSliceToQueryString takes a slice of elements and converts them into a query string.
IntToPointer is a function for converting integers into integer pointers.
IntWithinRange returns TRUE if an integer falls within a defined range, and FALSE if not.
MaybeInt is an internal function to be used by request methods in individual resource packages.
MaybeString is an internal function to be used by request methods in individual resource packages.
NormalizePathURL is used to convert rawPath to a fqdn, using basePath as a reference in the filesystem, if necessary.
NormalizeURL is an internal function to be used by provider clients.
ParseResponse is a helper function to parse http.Response to constituents.
RemainingKeys will inspect a struct and compare it to a map.
ResponseCodeIs returns true if this error is or contains an ErrUnexpectedResponseCode reporting that the request failed with the given response code.
WaitFor polls a predicate function, once per second, up to a context cancellation.

# Constants

AvailabilityAdmin indicates that an endpoint is only available to administrators.
AvailabilityInternal indicates that an endpoint is only available within the cluster's internal network.
AvailabilityPublic indicates that an endpoint is available to everyone on the internet.
DefaultUserAgent is the default User-Agent string set in the request header.
DefaultUserAgent is the default User-Agent string set in the request header.
IPv4 is used for IP version 4 addresses.
IPv6 is used for IP version 6 addresses.
RFC3339Milli describes a common time format used by some API responses.
No description provided by the author
RFC3339NoZ is the time format used in Heat (Orchestration).
RFC3339ZNoT is the time format used in Zun (Containers Service).
RFC3339ZNoTNoZ is another time format used in Zun (Containers Service).

# Variables

Convenience vars for EnabledState values.
Convenience vars for EnabledState values.

# Structs

AuthOptions stores information needed to authenticate to an OpenStack Cloud.
AuthScope allows a created token to be limited to a specific domain or project.
BaseError is an error type that all other error types embed.
EndpointOpts specifies search criteria used by queries against an OpenStack service catalog.
ErrAPIKeyProvided indicates that an APIKey was provided but can't be used.
ErrAppCredMissingSecret indicates that no Application Credential Secret was provided with Application Credential ID or Name.
ErrDomainIDOrDomainName indicates that a username was provided, but no domain to scope it.
ErrDomainIDWithToken indicates that a DomainID was provided, but token authentication is being used instead.
ErrDomainIDWithUserID indicates that a DomainID was provided, but unnecessary because a UserID is being used.
ErrDomainNameWithToken indicates that a DomainName was provided, but token authentication is being used instead.s.
ErrDomainNameWithUserID indicates that a DomainName was provided, but unnecessary because a UserID is being used.
ErrEndpointNotFound is returned when no available endpoints match the provided EndpointOpts.
ErrErrorAfterReauthentication is the error type returned when reauthentication succeeds, but an error occurs afterword (usually an HTTP error).
ErrInvalidInput is an error type used for most non-HTTP Gophercloud errors.
ErrMissingAnyoneOfEnvironmentVariables is the error when anyone of the environment variables is required in a particular situation but not provided by the user.
ErrMissingEnvironmentVariable is the error when environment variable is required in a particular situation but not provided by the user.
ErrMissingInput is the error when input is required in a particular situation but not provided by the user.
ErrMissingPassword indicates that no password was provided and no token is available.
ErrMultipleResourcesFound is the error when trying to retrieve a resource's ID by name and multiple resources have the user-provided name.
ErrResourceNotFound is the error when trying to retrieve a resource's ID by name and the resource doesn't exist.
ErrResult is an internal type to be used by individual resource packages, but its methods will be available on a wide variety of user-facing embedding types.
ErrScopeDomainIDOrDomainName indicates that a domain ID or Name was required in a Scope, but not present.
ErrScopeEmpty indicates that no credentials were provided in a Scope.
ErrScopeProjectIDAlone indicates that a ProjectID was provided with other constraints in a Scope.
ErrScopeProjectIDOrProjectName indicates that both a ProjectID and a ProjectName were provided in a Scope.
ErrServiceNotFound is returned when no service in a service catalog matches the provided EndpointOpts.
ErrTenantIDProvided indicates that a TenantID was provided but can't be used.
ErrTenantNameProvided indicates that a TenantName was provided but can't be used.
ErrTimeOut is the error type returned when an operations times out.
ErrUnableToReauthenticate is the error type returned when reauthentication fails.
ErrUnexpectedResponseCode is returned by the Request method when a response code other than those listed in OkCodes is encountered.
ErrUnexpectedType is the error when an unexpected type is encountered.
ErrUserIDWithToken indicates that a UserID was provided, but token authentication is being used instead.
ErrUsernameOrUserID indicates that neither username nor userID are specified, or both are at once.
ErrUsernameWithToken indicates that a Username was provided, but token authentication is being used instead.
HeaderResult is an internal type to be used by individual resource packages, but its methods will be available on a wide variety of user-facing embedding types.
Link is an internal type to be used in packages of collection resources that are paginated in a certain way.
ProviderClient stores details that are required to interact with any services within a specific provider's API.
RequestOpts customizes the behavior of the provider.Request() method.
Result is an internal type to be used by individual resource packages, but its methods will be available on a wide variety of user-facing embedding types.
ServiceClient stores details required to interact with a specific service API implemented by a provider.
UserAgent represents a User-Agent header.

# Interfaces

AuthResult is the result from the request that was used to obtain a provider client's Keystone token.

# Type aliases

Availability indicates to whom a specific service endpoint is accessible: the internet at large, internal networks only, or only to administrators.
EndpointLocator is an internal function to be used by provider implementations.
IPVersion is a type for the possible IP address versions.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
RetryFunc is a catch-all function for retrying failed API requests.