Applies to SUSE OpenStack Cloud 6

5 OpenStack Python SDK

The OpenStack Python Software Development Kit (SDK) is used to write Python automation scripts that create and manage resources in your OpenStack cloud. The SDK implements Python bindings to the OpenStack API, which enables you to perform automation tasks in Python by making calls on Python objects, rather than making REST calls directly. All OpenStack command-line tools are implemented using the Python SDK.

You should also be familiar with:

  • RESTful web services

  • HTTP/1.1

  • JSON and XML data serialization formats

5.1 Installing OpenStack SDK

Each OpenStack project has its own Python library. These libraries are bundled with the command-line clients. For example, the Python bindings for the Compute API are bundled with the python-novaclient package.

For details about how to install the clients, see .

5.2 Authenticate

When using the SDK, you must authenticate against an OpenStack endpoint before you can use OpenStack services. Each project uses a slightly different syntax for authentication.

You must typically authenticate against a specific version of a service. For example, a client might need to authenticate against Identity v2.0.

Python scripts that use the OpenStack SDK must have access to the credentials contained in the OpenStack RC file. Because credentials are sensitive information, do not include them in your scripts. This guide assumes that users source the PROJECT-openrc.sh file and access the credentials by using the environment variables in the Python scripts.

5.2.1 Authenticate against an Identity endpoint

To authenticate against the Identity v2.0 endpoint, instantiate a keystoneclient.v_20.client.Client (http://docs.openstack.org/developer/python-keystoneclient/api/keystoneclient.v2_0.client.html#keystoneclient.v2_0.client.Client) object:

from os import environ as env
import keystoneclient.v2_0.client as ksclient
keystone = ksclient.Client(auth_url=env['OS_AUTH_URL'],
                           username=env['OS_USERNAME'],
                           password=env['OS_PASSWORD'],
                           tenant_name=env['OS_TENANT_NAME'],
                           region_name=env['OS_REGION_NAME'])

After you instantiate a Client object, you can retrieve the token by accessing its auth_token attribute object:

import keystoneclient.v2_0.client as ksclient
keystone = ksclient.Client(...)
print keystone.auth_token

If the OpenStack cloud is configured to use public-key infrastructure (PKI) tokens, the Python script output looks something like this:

MIIQUQYJKoZIhvcNAQcCoIIQQjCCED4CAQExCTAHBgUrDgMCGjCCDqcGCSqGSIb3DQEHAaCCDpgE
gg6UeyJhY2Nlc3MiOiB7InRva2VuIjogeyJpc3N1ZWRfYXQiOiAiMjAxMy0xMC0yMFQxNjo1NjoyNi
4zNTg2MjUiLCAiZXhwaXJlcyI6ICIyMDEzLTEwLTIxVDE2OjU2OjI2WiIsICJpZCI6ICJwbGFjZWhv
...
R3g14FJ0BxtTPbo6WarZ+sA3PZwdgIDyGNI-0Oqv-8ih4gJC9C6wBCel1dUXJ0Mn7BN-SfuxkooVk6
e090bcKjTWet3CC8IEj7a6LyLRVTdvmKGA5-pgp2mS5fb3G2mIad4Zeeb-zQn9V3Xf9WUGxuiVu1Hn
fhuUpJT-s9mU7+WEC3-8qkcBjEpqVCvMpmM4INI=
Note
Note

This example shows a subset of a PKI token. A complete token is over 5000 characters long.

5.2.2 Authenticate against an Image service endpoint

To authenticate against an Image service endpoint, instantiate a glanceclient.v2.client.Client (http://docs.openstack.org/developer/python-glanceclient/api/glanceclient.v2.client.html#glanceclient.v2.client.Client) object:

from os import environ as env
import glanceclient.v2.client as glclient
import keystoneclient.v2_0.client as ksclient

keystone = ksclient.Client(auth_url=env['OS_AUTH_URL'],
                           username=env['OS_USERNAME'],
                           password=env['OS_PASSWORD'],
                           tenant_name=env['OS_TENANT_NAME'],
                           region_name=env['OS_REGION_NAME'])
glance_endpoint = keystone.service_catalog.url_for(service_type='image')
glance = glclient.Client(glance_endpoint, token=keystone.auth_token)

5.2.3 Authenticate against a Compute endpoint

To authenticate against a Compute endpoint, instantiate a novaclient.v_1_1.client.Client (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.client.html#novaclient.v1_1.client.Client) object:

from os import environ as env
import novaclient.v1_1.client as nvclient
nova = nvclient.Client(auth_url=env['OS_AUTH_URL'],
                       username=env['OS_USERNAME'],
                       api_key=env['OS_PASSWORD'],
                       project_id=env['OS_TENANT_NAME'],
                       region_name=env['OS_REGION_NAME'])

Alternatively, you can instantiate a novaclient.client.Client object and pass the version number:

from os import environ as env
import novaclient.client
nova = novaclient.client.Client("1.1", auth_url=env['OS_AUTH_URL'],
                                username=env['OS_USERNAME'],
                                api_key=env['OS_PASSWORD'],
                                project_id=env['OS_TENANT_NAME'],
                                region_name=env['OS_REGION_NAME'])

If you authenticate against an endpoint that uses a custom authentication back end, you must load the authentication plug-in and pass it to the constructor.

The Rackspace public cloud is an OpenStack deployment that uses a custom authentication back end. To authenticate against this cloud, you must install the rackspace-novaclient (https://pypi.python.org/pypi/rackspace-novaclient/) library that contains the Rackspace authentication plug-in, called rackspace. The following Python code shows the additional modifications required to instantiate a Client object that can authenticate against the Rackspace custom authentication back end.

import novaclient.auth_plugin
import novaclient.v1_1.client as nvclient
from os import environ as env
auth_system = 'rackspace'
auth_plugin = novaclient.auth_plugin.load_plugin('rackspace')
nova = nvclient.Client(auth_url=env['OS_AUTH_URL'],
                       username=env['OS_USERNAME'],
                       api_key=env['OS_PASSWORD'],
                       project_id=env['OS_TENANT_NAME'],
                       region_name=env['OS_REGION_NAME'],
                       auth_system='rackspace',
                       auth_plugin=auth_plugin)

If you set the OS_AUTH_SYSTEM environment variable, check for this variable in your Python script to determine whether you need to load a custom authentication back end:

import novaclient.auth_plugin
import novaclient.v1_1.client as nvclient
from os import environ as env
auth_system = env.get('OS_AUTH_SYSTEM', 'keystone')
if auth_system != "keystone":
  auth_plugin = novaclient.auth_plugin.load_plugin(auth_system)
else:
  auth_plugin = None
nova = nvclient.Client(auth_url=env['OS_AUTH_URL'],
                       username=env['OS_USERNAME'],
                       api_key=env['OS_PASSWORD'],
                       project_id=env['OS_TENANT_NAME'],
                       region_name=env['OS_REGION_NAME'],
                       auth_system=auth_system,
                       auth_plugin=auth_plugin)

5.2.4 Authenticate against a Networking endpoint

To authenticate against a Networking endpoint, instantiate a neutronclient.v_2_0.client.Client object:

from os import environ as env
from neutronclient.v2_0 import client as neutronclient
neutron = neutronclient.Client(auth_url=env['OS_AUTH_URL'],
                               username=env['OS_USERNAME'],
                               password=env['OS_PASSWORD'],
                               tenant_name=env['OS_TENANT_NAME'],
                               region_name=env['OS_REGION_NAME'])

You can also authenticate by explicitly specifying the endpoint and token:

from os import environ as env
import keystoneclient.v2_0.client as ksclient
from neutronclient.v2_0 import client as neutronclient
keystone = ksclient.Client(auth_url=env['OS_AUTH_URL'],
                           username=env['OS_USERNAME'],
                           password=env['OS_PASSWORD'],
                           tenant_name=env['OS_TENANT_NAME'],
                           region_name=env['OS_REGION_NAME'])
endpoint_url = keystone.service_catalog.url_for(service_type='network')
token = keystone.auth_token
neutron = neutronclient.Client(endpoint_url=endpoint_url, token=token)

5.3 Manage images

When working with images in the SDK, you will call both glance and nova methods.

5.3.1 List images

To list the available images, call the glanceclient.v2.images.Controller.list method:

import glanceclient.v2.client as glclient
glance = glclient.Client(...)
images = glance.images.list()

The images method returns a Python generator, as shown in the following interaction with the Python interpreter:

>>> images = glance.images.list()
>>> images
<generator object list at 0x105e9c2d0>
>>> list(images)
[{u'checksum': u'f8a2eeee2dc65b3d9b6e63678955bd83',
  u'container_format': u'ami',
  u'created_at': u'2013-10-20T14:28:10Z',
  u'disk_format': u'ami',
  u'file': u'/v2/images/dbc9b2db-51d7-403d-b680-3f576380b00c/file',
  u'id': u'dbc9b2db-51d7-403d-b680-3f576380b00c',
  u'kernel_id': u'c002c82e-2cfa-4952-8461-2095b69c18a6',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.2-x86_64-uec',
  u'protected': False,
  u'ramdisk_id': u'4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3',
  u'schema': u'/v2/schemas/image',
  u'size': 25165824,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:11Z',
  u'visibility': u'public'},
 {u'checksum': u'69c33642f44ca552ba4bb8b66ad97e85',
  u'container_format': u'ari',
  u'created_at': u'2013-10-20T14:28:09Z',
  u'disk_format': u'ari',
  u'file': u'/v2/images/4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3/file',
  u'id': u'4c1c9b4f-3fe9-425a-a1ec-1d8fd90b4db3',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.2-x86_64-uec-ramdisk',
  u'protected': False,
  u'schema': u'/v2/schemas/image',
  u'size': 3714968,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:10Z',
  u'visibility': u'public'},
 {u'checksum': u'c352f4e7121c6eae958bc1570324f17e',
  u'container_format': u'aki',
  u'created_at': u'2013-10-20T14:28:08Z',
  u'disk_format': u'aki',
  u'file': u'/v2/images/c002c82e-2cfa-4952-8461-2095b69c18a6/file',
  u'id': u'c002c82e-2cfa-4952-8461-2095b69c18a6',
  u'min_disk': 0,
  u'min_ram': 0,
  u'name': u'cirros-0.3.2-x86_64-uec-kernel',
  u'protected': False,
  u'schema': u'/v2/schemas/image',
  u'size': 4955792,
  u'status': u'active',
  u'tags': [],
  u'updated_at': u'2013-10-20T14:28:09Z',
  u'visibility': u'public'}]

5.3.2 Get image by ID

To retrieve an image object from its ID, call the glanceclient.v2.images.Controller.get method:

import glanceclient.v2.client as glclient
image_id = 'c002c82e-2cfa-4952-8461-2095b69c18a6'
glance = glclient.Client(...)
image = glance.images.get(image_id)

5.3.3 Get image by name

The Image service Python bindings do not support the retrieval of an image object by name. However, the Compute Python bindings enable you to get an image object by name. To get an image object by name, call the novaclient.v1_1.images.ImageManager.find method:

import novaclient.v1_1.client as nvclient
name = "cirros"
nova = nvclient.Client(...)
image = nova.images.find(name=name)

5.3.4 Upload an image

To upload an image, call the glanceclient.v2.images.ImageManager.create method:

import glanceclient.v2.client as glclient
imagefile = "/tmp/myimage.img"
glance = glclient.Client(...)
with open(imagefile) as fimage:
  glance.images.create(name="myimage", is_public=False, disk_format="qcow2",
                       container_format="bare", data=fimage)

5.4 Assign CORS headers to requests

Cross-Origin Resource Sharing (CORS) is a specification that defines how browsers and servers communicate across origins by using HTTP headers, such as those assigned by Object Storage API requests. The Object Storage API supports the following headers:

  • Access-Control-Allow-Credentials

  • Access-Control-Allow-Methods

  • Access-Control-Allow-Origin

  • Access-Control-Expose-Headers

  • Access-Control-Max-Age

  • Access-Control-Request-Headers

  • Access-Control-Request-Method

  • Origin

You can only assign these headers to objects. For more information, see www.w3.org/TR/access-control/ (http://www.w3.org/TR/access-control/).

This example assigns the file origin to the Origin header, which ensures that the file originated from a reputable source.

$ curl -i -X POST -H "Origin: example.com" -H "X-Auth-Token:
48e17715dfce47bb90dc2a336f63493a"
https://storage.example.com/v1/MossoCloudFS_c31366f1-9f1c-40dc-a
b92-6b3f0b5a8c45/ephotos
HTTP/1.1 204 No Content
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Access-Control-Allow-Origin: example.com
Access-Control-Expose-Headers: cache-control, content-language,
content-type, expires, last-modified, pragma, etag, x-timestamp, x-trans-id
X-Trans-Id: tx979bfe26be6649c489ada-0054cba1d9ord1
Date: Fri, 30 Jan 2015 15:23:05 GMT

5.5 Schedule objects for deletion

To determine whether your Object Storage system supports this feature, see . Alternatively, check with your service provider.

Scheduling an object for deletion is helpful for managing objects that you do not want to permanently store, such as log files, recurring full backups of a dataset, or documents or images that become outdated at a specified time.

To schedule an object for deletion, include one of these headers with the PUT or POST request on the object:

X-Delete-At

A UNIX epoch timestamp, in integer form. For example, 1348691905 represents Wed, 26 Sept 2012 20:38:25 GMT. It specifies the time you want the object to expire, no longer be served, and be deleted completely from the object store.

X-Delete-After

An integer value which specifies the number of seconds from the time of the request to when you want to delete the object. This header is converted to a X-Delete-At header that is set to the sum of the X-Delete-After value plus the current time, in seconds.

Note
Note

Use http://www.epochconverter.com/ (http://www.epochconverter.com/) to convert dates to and from epoch timestamps and for batch conversions.

Use the POST method to assign expiration headers to existing objects that you want to expire.

In this example, the X-Delete-At header is assigned a UNIX epoch timestamp in integer form for Mon, 11 Jun 2012 15:38:25 GMT.

$ curl -i publicURL/marktwain/goodbye -X PUT -H "X-Auth-Token: token" \
  -H "X-Delete-At: 1390581073" -H "Content-Length: 14" -H \
  "Content-Type: application/octet-stream"

In this example, the X-Delete-After header is set to 864000 seconds. The object expires after this time.

PUT /<api version>/<account>/<container>/<object> HTTP/1.1
Host: storage.example.com
X-Auth-Token: eaaafd18-0fed-4b3a-81b4-663c99ec1cbb
Content-Type: image/jpeg
X-Delete-After: 864000

5.6 Configure access and security for instances

When working with images in the SDK, you will call novaclient methods.

5.6.1 Add a keypair

To generate a keypair, call the novaclient.v1_1.keypairs.KeypairManager.create (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.keypairs.html#novaclient.v1_1.keypairs.KeypairManager.create) method:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
keypair_name = "staging"
keypair = nova.keypairs.create(name=keypair_name)
print keypair.private_key

The Python script output looks something like this:

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA8XkaMqInSPfy0hMfWO+OZRtIgrQAbQkNcaNHmv2GN2G6xZlb\nuBRux5Xk/6SZ
ABaNPm1nRWm/ZDHnxCsFTcAl2LYOQXx3Cl2qKNY4r2di4G48GAkd\n7k5lDP2RgQatUM8npO0CD9PU
...
mmrceYYK08/lQ7JKLmVkdzdQKt77+v1oBBuHiykLfI6h1m77NRDw9r8cV\nzczYeoALifpjTPMkKS8
ECfDCuDn/vc9K1He8CRaJHf8AMLQLM3MN
-----END RSA PRIVATE KEY-----

You typically write the private key to a file to use it later. The file must be readable and writeable by only the file owner; otherwise, the SSH client will refuse to read the private key file. The safest way is to create the file with the appropriate permissions, as shown in the following example:

import novaclient.v1_1.client as nvclient
import os
nova = nvclient.Client(...)
keypair_name = "staging"
private_key_filename = "/home/alice/id-staging"
keypair = nova.keypairs.create(name=keypair_name)

# Create a file for writing that can only be read and written by
owner
fp = os.open(private_key_filename, os.O_WRONLY | os.O_CREAT, 0o600)
with os.fdopen(fp, 'w') as f:
    f.write(keypair.private_key)

5.6.2 Import a keypair

If you have already generated a keypair with the public key located at ~/.ssh/id_rsa.pub, pass the contents of the file to the novaclient.v1_1.keypairs.KeypairManager.create (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.keypairs.html#novaclient.v1_1.keypairs.KeypairManager.create) method to import the public key to Compute:

import novaclient.v1_1.client as nvclient
import os.path
with open(os.path.expanduser('~/.ssh/id_rsa.pub')) as f:
    public_key = f.read()
nova = nvclient.Client(...)
nova.keypairs.create('mykey', public_key)

5.6.3 List keypairs

To list keypairs, call the novaclient.v1_1.keypairs.KeypairManager.list (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.keypairs.html#novaclient.v1_1.keypairs.KeypairManager.list) method:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
keypairs = nova.keypairs.list()

5.6.4 Create and manage security groups

To list security groups for the current project, call the novaclient.v_1.security_groups.SecurityGroupManager.list (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_groups.html#novaclient.v1_1.security_groups.SecurityGroupManager.list) method:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
security_groups = nova.security_groups.list()

To create a security group with a specified name and description, call the novaclient.v_1.security_groups.SecurityGroupManager.create (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_groups.html#novaclient.v1_1.security_groups.SecurityGroupManager.create) method:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
nova.security_groups.create(name="web", description="Web servers")

To delete a security group, call the novaclient.v_1.security_groups.SecurityGroupManager.delete (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_groups.html#novaclient.v1_1.security_groups.SecurityGroupManager.delete) method, passing either a novaclient.v1_1.security_groups.SecurityGroup (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_groups.html#novaclient.v1_1.security_groups.SecurityGroup) object or group ID as an argument:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
nova.security_groups.delete(group)
# The following lines would also delete the group:
# nova.security_groups.delete(group.id)
# group.delete()

5.6.5 Create and manage security group rules

Access the security group rules from the rules attribute of a novaclient.v1_1.security_groups.SecurityGroup (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_groups.html#novaclient.v1_1.security_groups.SecurityGroup) object:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
print group.rules

To add a rule to a security group, call the novaclient.v1_1.security_group_rules.SecurityGroupRuleManager.create (http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.security_group_rules.html#novaclient.v1_1.security_group_rules.SecurityGroupRuleManager.create) method:

import novaclient.v1_1.client as nvclient
nova = nvclient.Client(...)
group = nova.security_groups.find(name="web")
# Add rules for ICMP, tcp/80 and tcp/443
nova.security_group_rules.create(group.id, ip_protocol="icmp",
                                 from_port=-1, to_port=-1)
nova.security_group_rules.create(group.id, ip_protocol="tcp",
                                 from_port=80, to_port=80)
nova.security_group_rules.create(group.id, ip_protocol="tcp",
                                 from_port=443, to_port=443)

5.7 Networking

To use the information in this section, you should have a general understanding of OpenStack Networking, OpenStack Compute, and the integration between the two. You should also have access to a plug-in that implements the Networking API v2.0.

5.7.1 Set environment variables

Make sure that you set the relevant environment variables.

As an example, see the sample shell file that sets these variables to get credentials:

export OS_USERNAME="admin"
export OS_PASSWORD="password"
export OS_TENANT_NAME="admin"
export OS_AUTH_URL="http://IPADDRESS/v2.0"

5.7.2 Get credentials

The examples in this section use the get_credentials method:

def get_credentials():
    d = {}
    d['username'] = os.environ['OS_USERNAME']
    d['password'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['tenant_name'] = os.environ['OS_TENANT_NAME']
    return d

This code resides in the credentials.py file, which all samples import.

Use the get_credentials() method to populate and get a dictionary:

credentials = get_credentials()

5.7.3 Get Nova credentials

The examples in this section use the get_nova_credentials method:

def get_nova_credentials():
    d = {}
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    return d

This code resides in the credentials.py file, which all samples import.

Use the get_nova_credentials() method to populate and get a dictionary:

nova_credentials = get_nova_credentials()

5.7.5 Create network

The following program creates a network:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials

network_name = 'sample_network'
credentials = get_credentials()
neutron = client.Client(**credentials)
try:
    body_sample = {'network': {'name': network_name,
                   'admin_state_up': True}}

    netw = neutron.create_network(body=body_sample)
    net_dict = netw['network']
    network_id = net_dict['id']
    print('Network %s created' % network_id)

    body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                          'ip_version': 4, 'network_id': network_id}]}

    subnet = neutron.create_subnet(body=body_create_subnet)
    print('Created subnet %s' % subnet)
finally:
    print("Execution completed")

5.7.6 List networks

The following program lists networks:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
netw = neutron.list_networks()

print_values(netw, 'networks')

For print_values, see Section 5.7.4, “Print values”.

5.7.7 Create ports

The following program creates a port:

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v1_1.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# Replace with server_id and network_id from your environment

server_id = '9a52795a-a70d-49a8-a5d0-5b38d78bd12d'
network_id = 'ce5d204a-93f5-43ef-bd89-3ab99ad09a9a'
server_detail = nova_client.servers.get(server_id)
print(server_detail.id)

if server_detail != None:
    credentials = get_credentials()
    neutron = client.Client(**credentials)

    body_value = {
                     "port": {
                             "admin_state_up": True,
                             "device_id": server_id,
                             "name": "port1",
                             "network_id": network_id
                      }
                 }
    response = neutron.create_port(body=body_value)
    print(response)

For get_nova_credentials, see Section 5.7.3, “Get Nova credentials”.

For get_credentials, see Section 5.7.2, “Get credentials”.

5.7.8 List ports

The following program lists ports:

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
ports = neutron.list_ports()
print_values(ports, 'ports')

For get_credentials see Section 5.7.2, “Get credentials”.

For print_values, see Section 5.7.4, “Print values”.

5.7.9 List server ports

The following program lists the ports for a server:

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v1_1.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials
from utils import print_values_server

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# change these values according to your environment

server_id = '9a52795a-a70d-49a8-a5d0-5b38d78bd12d'
network_id = 'ce5d204a-93f5-43ef-bd89-3ab99ad09a9a'
server_detail = nova_client.servers.get(server_id)
print(server_detail.id)

if server_detail is not None:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    ports = neutron.list_ports()

    print_values_server(ports, server_id, 'ports')
    body_value = {'port': {
        'admin_state_up': True,
        'device_id': server_id,
        'name': 'port1',
        'network_id': network_id,
        }}

    response = neutron.create_port(body=body_value)
    print(response)

5.7.10 Create router and add port to subnet

This example queries OpenStack Networking to create a router and add a port to a subnet.

  1. Import the following modules:

    from neutronclient.v2_0 import client
    import novaclient.v1_1.client as nvclient
    from credentials import get_credentials
    from credentials import get_nova_credentials
    from utils import print_values_server
  2. Get Nova Credentials. See :ref:'Get Nova credentials <get-nova-credentials>'.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = nvclient.Client(**credentials)
  4. Create a router and add a port to the subnet:

    # Replace with network_id from your environment
    
    network_id = '81bf592a-9e3f-4f84-a839-ae87df188dc1'
    
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    neutron.format = json
    request = {'router': {'name': 'router name',
                          'admin_state_up': True}}
    
    router = neutron.create_router(request)
    router_id = router['router']['id']
    # for example: '72cf1682-60a8-4890-b0ed-6bad7d9f5466'
    router = neutron.show_router(router_id)
    print(router)
    body_value = {'port': {
        'admin_state_up': True,
        'device_id': router_id,
        'name': 'port1',
        'network_id': network_id,
        }}
    
    response = neutron.create_port(body=body_value)
    print(response)
    print("Execution Completed")

5.7.10.1 Create router: complete code listing example

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v1_1.client as nvclient
from credentials import get_credentials
from credentials import get_nova_credentials
from utils import print_values_server

credentials = get_nova_credentials()
nova_client = nvclient.Client(**credentials)

# Replace with network_id from your environment

network_id = '81bf592a-9e3f-4f84-a839-ae87df188dc1'
try:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    neutron.format = 'json'
    request = {'router': {'name': 'router name',
                          'admin_state_up': True}}
    router = neutron.create_router(request)
    router_id = router['router']['id']
    # for example: '72cf1682-60a8-4890-b0ed-6bad7d9f5466'
    router = neutron.show_router(router_id)
    print(router)
    body_value = {'port': {
        'admin_state_up': True,
        'device_id': router_id,
        'name': 'port1',
        'network_id': network_id,
        }}

    response = neutron.create_port(body=body_value)
    print(response)
finally:
    print("Execution completed")

5.7.11 Delete a network

This example queries OpenStack Networking to delete a network.

To delete a network:

  1. Import the following modules:

    from neutronclient.v2_0 import client
    from credentials import get_credentials
  2. Get credentials. See Section 5.7.3, “Get Nova credentials”.

  3. Instantiate the neutron client object by using the credentials dictionary object:

    neutron = client.Client(**credentials)
  4. Delete the network:

    body_sample = {'network': {'name': network_name,
                   'admin_state_up': True}}
    
    netw = neutron.create_network(body=body_sample)
    net_dict = netw['network']
    network_id = net_dict['id']
    print('Network %s created' % network_id)
    
    body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                          'ip_version': 4, 'network_id': network_id}]}
    
    subnet = neutron.create_subnet(body=body_create_subnet)
    print('Created subnet %s' % subnet)
    
    neutron.delete_network(network_id)
    print('Deleted Network %s' % network_id)
    
    print("Execution completed")

5.7.11.1 Delete network: complete code listing example

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials

network_name = 'temp_network'
credentials = get_credentials()
neutron = client.Client(**credentials)
try:
    body_sample = {'network': {'name': network_name,
                   'admin_state_up': True}}

    netw = neutron.create_network(body=body_sample)
    net_dict = netw['network']
    network_id = net_dict['id']
    print('Network %s created' % network_id)

    body_create_subnet = {'subnets': [{'cidr': '192.168.199.0/24',
                          'ip_version': 4, 'network_id': network_id}]}

    subnet = neutron.create_subnet(body=body_create_subnet)
    print('Created subnet %s' % subnet)

    neutron.delete_network(network_id)
    print('Deleted Network %s' % network_id)
finally:
    print("Execution Completed")

5.7.12 List routers

This example queries OpenStack Networking to list all routers.

  1. Import the following modules:

    from neutronclient.v2_0 import client
    from credentials import get_credentials
    from utils import print_values
  2. Get credentials. See Section 5.7.3, “Get Nova credentials”.

  3. Instantiate the neutron client object by using the credentials dictionary object:

    neutron = client.Client(**credentials)
  4. List the routers:

    routers_list = neutron.list_routers(retrieve_all=True)
    print_values(routers_list, 'routers')
    print("Execution completed")

    For print_values, see Section 5.7.4, “Print values”.

5.7.12.1 List routers: complete code listing example

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

try:
    credentials = get_credentials()
    neutron = client.Client(**credentials)
    routers_list = neutron.list_routers(retrieve_all=True)
    print_values(routers_list, 'routers')
finally:
    print("Execution completed")

5.7.13 List security groups

This example queries OpenStack Networking to list security groups.

  1. Import the following modules:

    from neutronclient.v2_0 import client
    from credentials import get_credentials
    from utils import print_values
  2. Get credentials. See Section 5.7.2, “Get credentials”.

  3. Instantiate the neutron client object by using the credentials dictionary object:

    neutron = client.Client(**credentials)
  4. List Security groups

    sg = neutron.list_security_groups()
    print(sg)

5.7.13.1 List security groups: complete code listing example

 #!/usr/bin/env python
 from neutronclient.v2_0 import client
 from credentials import get_credentials
 from utils import print_values

 credentials = get_credentials()
 neutron = client.Client(**credentials)
 sg = neutron.list_security_groups()
 print(sg)

.. note::

  OpenStack Networking security groups are case-sensitive while the
  nova-network security groups are case-insensitive.

5.7.14 List subnets

This example queries OpenStack Networking to list subnets.

  1. Import the following modules:

    from neutronclient.v2_0 import client
    from credentials import get_credentials
    from utils import print_values
  2. Get credentials. See :ref:'Get credentials <get-credentials>'.

  3. Instantiate the neutron client object by using the credentials dictionary object:

    neutron = client.Client(**credentials)
  4. List subnets:

    subnets = neutron.list_subnets()
    print(subnets)

5.7.14.1 List subnets: complete code listing example

#!/usr/bin/env python
from neutronclient.v2_0 import client
from credentials import get_credentials
from utils import print_values

credentials = get_credentials()
neutron = client.Client(**credentials)
subnets = neutron.list_subnets()
print(subnets)

5.8 Compute

To use the information in this section, you must be familiar with OpenStack Compute.

5.8.1 Set environment variables

To set up environmental variables and authenticate against Compute API endpoints, see Section 5.2, “Authenticate”.

5.8.2 Get OpenStack credentials (API v2)

This example uses the get_nova_credentials_v2 method:

def get_nova_credentials_v2():
    d = {}
    d['version'] = '2'
    d['username'] = os.environ['OS_USERNAME']
    d['api_key'] = os.environ['OS_PASSWORD']
    d['auth_url'] = os.environ['OS_AUTH_URL']
    d['project_id'] = os.environ['OS_TENANT_NAME']
    return d

This code resides in the credentials.py file, which all samples import.

Use the get_nova_credentials_v2() method to populate and get a dictionary:

credentials = get_nova_credentials_v2()

5.8.3 List servers (API v2)

The following program lists servers by using the Compute API v2.

  1. Import the following modules:

    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
  2. Get Nova credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. List servers by calling servers.list on nova_client object:

    print(nova_client.servers.list())

5.8.3.1 List server code listing example

#!/usr/bin/env python
from credentials import get_nova_credentials_v2
from novaclient.client import Client

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

print(nova_client.servers.list())

5.8.4 Create server (API v2)

The following program creates a server (VM) by using the Compute API v2.

  1. Import the following modules:

    import time
    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
  2. Get OpenStack credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. Get the flavor and image to use to create a server. This code uses the cirros image, the m1.tiny flavor, and the private network:

    image = nova_client.images.find(name="cirros")
    flavor = nova_client.flavors.find(name="m1.tiny")
    net = nova_client.networks.find(label="private")
  5. To create the server, use the network, image, and flavor:

    nics = [{'net-id': net.id}]
    instance = nova_client.servers.create(name="vm2", image=image,
    flavor=flavor, key_name="keypair-1", nics=nics)
  6. Run the "Sleep for five seconds" command, and determine whether the server/vm was created by calling nova_client.servers.list():

    print("Sleeping for 5s after create command")
    time.sleep(5)
    print("List of VMs")
    print(nova_client.servers.list())

5.8.4.1 Create server code listing example

#!/usr/bin/env python
import time
from credentials import get_nova_credentials_v2
from novaclient.client import Client

try:
    credentials = get_nova_credentials_v2()
    nova_client = Client(**credentials)

    image = nova_client.images.find(name="cirros")
    flavor = nova_client.flavors.find(name="m1.tiny")
    net = nova_client.networks.find(label="private")
    nics = [{'net-id': net.id}]
    instance = nova_client.servers.create(name="vm2", image=image,
                                      flavor=flavor, key_name="keypair-1", nics=nics)
    print("Sleeping for 5s after create command")
    time.sleep(5)
    print("List of VMs")
    print(nova_client.servers.list())
finally:
    print("Execution Completed")

5.8.5 Delete server (API v2)

The following program deletes a server (VM) by using the Compute API v2.

  1. Import the following modules:

    import time
    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
  2. Get Nova credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. Determine whether the vm1 server exists:

    1. List servers: servers_list.

    2. Iterate over servers_list and compare name with vm1.

    3. If true, set the variable name server_exists to True and break from the for loop:

    servers_list = nova_client.servers.list()
    server_del = "vm1"
    server_exists = False
    
    for s in servers_list:
        if s.name == server_del:
            print("This server %s exists" % server_del)
            server_exists = True
            break
  5. If the server exists, run the delete method of the nova_client.servers object:

    nova_client.servers.delete(s)

5.8.5.1 Delete server code example

#!/usr/bin/env python
from credentials import get_nova_credentials_v2
from novaclient.client import Client

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

servers_list = nova_client.servers.list()
server_del = "vm1"
server_exists = False

for s in servers_list:
    if s.name == server_del:
        print("This server %s exists" % server_del)
        server_exists = True
        break
if not server_exists:
    print("server %s does not exist" % server_del)
else:
    print("deleting server..........")
    nova_client.servers.delete(s)
    print("server %s deleted" % server_del)

5.8.6 Update server (API v2)

The following program updates the name of a server (VM) by using the Compute API v2.

  1. Import the following modules:

    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
    from utils import print_server

    print_server is a method defined in utils.py and prints the server details as shown in the code listing below:

    def print_server(server):
        print("-"*35)
        print("server id: %s" % server.id)
        print("server name: %s" % server.name)
        print("server image: %s" % server.image)
        print("server flavor: %s" % server.flavor)
        print("server key name: %s" % server.key_name)
        print("user_id: %s" % server.user_id)
        print("-"*35)
  2. Get OpenStack Credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. Get the server instance using server_id and print the details by calling print_server method:

    server_id = '99889c8d-113f-4a7e-970c-77f1916bfe14'
    server = nova_client.servers.get(server_id)
    n = server.name
    print_server(server)
  5. Call server.update on the server object with the new value for name variable:

    server.update(name = n + '1')
  6. Get the updated instance of the server:

    server_updated = nova_client.servers.get(server_id)
  7. Call print_server again to check the update server details:

    print_server(server_updated)

5.8.6.1 Update server code listing example

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_server

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

# Change the server_id specific to your environment

server_id = '99889c8d-113f-4a7e-970c-77f1916bfe14'
server = nova_client.servers.get(server_id)
n = server.name
print_server(server)

server.update(name=n +'1')
server_updated = nova_client.servers.get(server_id)
print_server(server_updated)

5.8.7 List flavors (API v2)

The following program lists flavors and their details by using the Compute API v2.

  1. Import the following modules:

    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
    from utils import print_flavors

    The print_flavors method is defined in utils.py and prints the flavor details:

    def print_flavors(flavor_list):
        for flavor in flavor_list:
           print("-"*35)
           print("flavor id : %s" % flavor.id)
           print("flavor name : %s" % flavor.name)
           print("-"*35)
  2. Get OpenStack credentials. Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. List flavors by calling list() on nova_client.flavors object:

    flavors_list =  nova_client.flavors.list()
  5. Print the flavor details, id and name by calling print_flavors:

    print_flavors(flavors_list)

5.8.7.1 List flavors code listing example

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_flavors

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)

flavors_list = nova_client.flavors.list()
print_flavors(flavors_list)

5.8.8 List floating IPs (API v2)

The following program lists the floating IPs and their details by using the Compute API v2.

  1. Import the following modules:

    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
    from utils import print_values_ip

    The print_values_ip method is defined in utils.py and prints the floating_ip object details:

    def print_values_ip(ip_list):
        ip_dict_lisl = []
        for ip in ip_list:
            print("-"*35)
            print("fixed_ip : %s" % ip.fixed_ip)
            print("id : %s" % ip.id)
            print("instance_id : %s" % ip.instance_id)
            print("ip : %s" % ip.ip)
            print("pool : %s" % ip.pool)
  2. Get OpenStack credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. List floating IPs by calling list() on nova_client.floating_ips object:

    ip_list = nova_client.floating_ips.list()
  5. Print the floating IP object details by calling print_values_ip:

    print_values_ip(ip_list)

5.8.8.1 List floating IPs code listing example

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_values_ip

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)
ip_list = nova_client.floating_ips.list()
print_values_ip(ip_list)

5.8.9 List hosts (API v2)

The following program lists the hosts by using the Compute API v2.

  1. Import the following modules:

    from credentials import get_nova_credentials_v2
    from novaclient.client import Client
    from utils import print_hosts

    The print_hosts method is defined in utils.py and prints the host object details:

    def print_hosts(host_list):
        for host in host_list:
           print("-"*35)
           print("host_name : %s" % host.host_name)
           print("service : %s" % host.service)
           print("zone : %s" % host.zone)
           print("-"*35)
  2. Get OpenStack credentials. See Section 5.8.2, “Get OpenStack credentials (API v2)”.

  3. Instantiate the nova_client client object by using the credentials dictionary object:

    nova_client = Client(**credentials)
  4. List hosts by calling list() on nova_client.hosts object:

    host_list = nova_client.hosts.list()
  5. Print the host object details by calling print_hosts(host_list):

    print_hosts(host_list)

5.8.9.1 List hosts code listing example

#!/usr/bin/env python

from credentials import get_nova_credentials_v2
from novaclient.client import Client
from utils import print_hosts

credentials = get_nova_credentials_v2()
nova_client = Client(**credentials)
host_list = nova_client.hosts.list()

print_hosts(host_list)
Print this page