Applies to SUSE OpenStack Cloud 7

5 OpenStack Python SDK

5.1 Overview

OpenStack provides four different options for interacting with its APIs from Python, each targeting a slightly different user:

  • OpenStack SDK

  • shade

  • Per-project client libraries

  • Direct REST calls via keystoneauth

You should also be familiar with:

  • RESTful web services

  • HTTP/1.1

  • JSON and data serialization formats

5.1.1 OpenStack 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.

New users should default to coding against the OpenStack SDK.

5.1.2 shade

shade is an abstraction library focused on hiding implementation differences between OpenStack clouds. While the OpenStack SDK presents a clean object interface to the underlying REST APIs, shade hides them if doing so is advantageous. If you plan on running the same Python program against many OpenStack clouds, you may want to use shade - but if you need to access any features of a cloud that do not have a cloud-neutral abstraction mapping, you will be unable to do so with shade.

5.1.3 Per-project client libraries

Each OpenStack project produces a client library that wraps its own REST API. Unless there is no other choice for some reason, the per-project libraries should be avoided.

5.1.4 Direct REST calls via keystoneauth

All of OpenStack's APIs are actually REST APIs. The keystoneauth library provides an object that looks very much like a Session object from the Python requests library that handles all of the authentication for you. If you are more comfortable just dealing with REST or if there is a feature implemented in your cloud that has not seen support in any of the libraries yet, this option is for you.

5.2 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.3 Authenticate

When using the SDK, you must authenticate against an OpenStack endpoint before you can use OpenStack services. Because all projects use Keystone for authentication, the process is the same no matter which service or library you have decided to use. Each library also has more advanced and complicated ways to do things, should those be needed.

There are two basic ways to deal with your cloud config and credentials:

  • Environment variables via an openrc.sh file

  • clouds.yaml config file

The environment variables have been around the longest and are the form you are most likely to receive from your cloud provider. If you have one and only one cloud account, they are the most convenient way.

clouds.yaml is a bit newer and was designed to help folks who have more than one OpenStack cloud that they are using.

5.4 Create a Legacy Client Object

All of the legacy client objects can be constructed the same way - the only difference is the first argument to make_client. The examples will use compute to get a nova client, but neutron can be accessed instead by replacing compute with network.

To use the legacy python-novaclient with a Compute endpoint, instantiate a novaclient.v2.client.Client object using os-client-config:

import os_client_config

nova = os_client_config.make_client(
    'compute',
    auth_url='https://example.com',
    username='example-openstack-user',
    password='example-password',
    project_name='example-project-name',
    region_name='example-region-name')

If you desire a specific micro-version of the Nova API, you can pass that as the version parameter:

import os_client_config

nova = os_client_config.make_client(
    'compute',
    version='2.10',
    auth_url='https://example.com',
    username='example-openstack-user',
    password='example-password',
    project_name='example-project-name',
    region_name='example-region-name')

If you authenticate against an endpoint that uses a custom authentication back end, you must provide the name of the plugin in the auth_type parameter.

For instance, the Rackspace public cloud is an OpenStack deployment that has an optional custom authentication back end. While normal keystone password authentication works perfectly well, you may want to use the custom Rackspace keystoneauth API Key plugin found in rackspace-keystoneauth-plugin.

nova = os_client_config.make_client(
    'compute',
    auth_type='rackspace_apikey',
    auth_url='https://example.com',
    username='example-openstack-user',
    api_key='example-apikey',
    project_name='example-project-name',
    region_name='example-region-name')

5.5 Manage images

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

5.5.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.5.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.5.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.v2.images.ImageManager.find method:

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

5.5.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.6 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/.

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.7 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 EpochConverter 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.8 Configure access and security for instances

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

5.8.1 Add a keypair

To generate a keypair, call the novaclient.v1_1.keypairs.KeypairManager.create method:

import novaclient.v2.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.v2.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.8.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 method to import the public key to Compute:

import novaclient.v2.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.8.3 List keypairs

To list keypairs, call the novaclient.v1_1.keypairs.KeypairManager.list method:

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

5.8.4 Create and manage security groups

To list security groups for the current project, call the novaclient.v_1.security_groups.SecurityGroupManager.list method:

import novaclient.v2.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 method:

import novaclient.v2.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 method, passing either a novaclient.v1_1.security_groups.SecurityGroup object or group ID as an argument:

import novaclient.v2.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.8.5 Create and manage security group rules

Access the security group rules from the rules attribute of a novaclient.v1_1.security_groups.SecurityGroup object:

import novaclient.v2.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 method:

import novaclient.v2.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.9 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.9.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.9.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.9.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.9.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.9.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.9.4, “Print values”.

5.9.7 Create ports

The following program creates a port:

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v2.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.9.3, “Get Nova credentials”.

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

5.9.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.9.2, “Get credentials”.

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

5.9.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.v2.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.9.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.v2.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.9.10.1 Create router: complete code listing example

#!/usr/bin/env python
from neutronclient.v2_0 import client
import novaclient.v2.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.9.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.9.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.9.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.9.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.9.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.9.4, “Print values”.

5.9.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.9.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.9.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.9.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
Note

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

5.9.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.9.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.10 Compute

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

5.10.1 Set environment variables

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

5.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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.10.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