Openstack services obtaining tokens

I had a difficult time finding information on how a service might obtain a token to talk to other services. There is certainly a lot of code to pull from but the calls are quite distributed. I got most of this from the ceilometer project.

The basic idea is that you register the keystoneauth1 options into your configuration, then instantiate it, then you can make calls to services.

I’m using a global session in this code. You can just as easily drop that and generate a new session every time you need to talk to something.

This code will obtain a token using the information from the [service_credentials] section in /etc/test/test.conf and make a request to nova and print the results.

from keystoneauth1 import loading as ks_loading
from oslo_config import cfg
from novaclient import client as nova_client

CONF = cfg.CONF

CFG_GROUP = "service_credentials"

_SESSION = None
_AUTH = None

def get_session():
    global _SESSION
    global _AUTH

    if not _AUTH:
        auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'service_credentials')

    if not _SESSION:
        _SESSION = ks_loading.load_session_from_conf_options(
            CONF, CFG_GROUP, auth=auth)

    return _SESSION

def novaclient():
    session = get_session()
    return nova_client.Client('2.1', session=session)

def register_keystoneauth_opts(conf):
    ks_loading.register_auth_conf_options(conf, CFG_GROUP)
    ks_loading.register_session_conf_options(
        conf, CFG_GROUP,
        deprecated_opts={'cacert': [
            cfg.DeprecatedOpt('os-cacert', group=CFG_GROUP),
            cfg.DeprecatedOpt('os-cacert', group="DEFAULT")]
        })

register_keystoneauth_opts(cfg.CONF)
CONF([], project='test')

x = novaclient()
print x.flavors.list()

Create a configuration file

# mkdir /etc/test

Add this to /etc/test/test.conf (note that I’m re-using the nova credentials for this demo):

[service_credentials]
region_name=RegionOne
auth_type=password
auth_url=http://192.168.0.1:5000/
project_name=services
project_domain_name=Default
username=nova
user_domain_name=Default
password=Secret

This was done using a Newton pre-release installation I’m developing on.