Getting a rax image id

If you use the Rackspace API to create servers (e.g. via the ansible module), you need to know the id of the image you want to use.

It’s pretty easy to make the list request using curl, but the json is quite noisy and it’s paged; so I wrote a script:

#!/usr/bin/env python2

# https://developer.rackspace.com/docs/cloud-images/quickstart/

import os
import json
import urllib2
from urlparse import urlparse

username = os.environ['RAX_USERNAME']
api_key = os.environ['RAX_API_KEY']
region = os.environ['RAX_REGION']

url = 'https://identity.api.rackspacecloud.com/v2.0/tokens'
headers = {
    'Content-Type': 'application/json'
}
req_body = {
    'auth': {
        'RAX-KSKEY:apiKeyCredentials': {
            'username': username,
            'apiKey': api_key
        }
    }
}

data = json.dumps(req_body)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
res_body = json.loads(response.read())
access = res_body['access']
token = access['token']['id']
#print "Token: {0}".format(token)
endpoints = [s for s in access['serviceCatalog'] if s['name'] == 'cloudImages'][0]['endpoints']
endpoint = [e for e in endpoints if e['region'] == region][0]['publicURL']
#print "Endpoint: {0}".format(endpoint)
url = '{0}/images'.format(endpoint)
#print "Url: {0}".format(url)
images = []

while url != None :
    headers = {
        'X-Auth-Token': token
    }
    req = urllib2.Request(url, headers=headers)
    response = urllib2.urlopen(req)
    res_body = json.loads(response.read())
    images = images + map(lambda i: {'id': i['id'], 'name': i['name']}, res_body['images'])

    if 'next' in res_body :
        u = urlparse(req.get_full_url())
        next_page = '{0}://{1}{2}'.format(u.scheme, u.netloc, res_body['next'])
        #print "Next: {0}".format(next_page)
        url = next_page
    else :
        url = None

for i in images:
    print "{0}: {1}".format(i['name'], i['id'])

UPDATE: the rax module allows you to use a name now (e.g. “Debian 8 (Jessie) (PVHVM)”), but this can still be useful for listing other rax “things”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s