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


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 = ''
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(
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(
    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”