As a cloud software engineer working closely with devops like tasks one of the questions most often asked by others working with our OpenStack installation is how to programmatically access and manage the OpenStack services.
From the user’s point of view the lowest level of access is provided by multiple OpenStack APIs (e.g. Compute API, Identity API, Object Storage API) while the more often used level of access is via command-line APIs. Under the hood these command-line APIs are just Python applications making requests to OpenStack ReST APIs. To interact with the OpenStack APIs the applications must have a few variables assigned (namely user credentials and the Keystone authentication URL) and they usually use the following workflow.
- Make a request to Keystone API’s authentication URL to retrieve Identity API details
- Make a request to Keystone API’s tokens resource with user credentials to retrieve authentication token with list of available OpenStack API endpoints
- Make a request to chosen OpenStack API with the authentication token
One can add –debug argument to any of the OpenStack command line API application to see the actual requests happening. These applications can take the user credentials as command line arguments or from specific environment variables which are set when OpenStack RC file (downloadable from the Horizon Web UI) is sourced.
However, to write Python applications using the OpenStack API’s the most convenient way is probably by using the command-line API libraries from one’s Python code. Only downside is that these APIs are still bad poorly documented, which is probably why people are not that often aware of them. But the usage is pretty straightforward. To begin with one imports the specific client library after which the client is instantiated with user credentials and the authentication URL. In the example below I have created two helper functions: one to read certain key from stdin if the key is not available as environment variable, and another function to return OpenStack Nova client object with required arguments read either from command line or from environment variables.
The main function uses the nova client to list all OpenStack instances after which it creates a new instance. Once that instance is in active state all instances are listed again. In the end the instance is queried by its name and the instance is deleted.
Another example how to work with Nova client library can be found e.g. from our Pouta Blueprints code.