Skip to content

Instantly share code, notes, and snippets.

@hammer
Created December 7, 2008 09:13
Show Gist options
  • Save hammer/33068 to your computer and use it in GitHub Desktop.
Save hammer/33068 to your computer and use it in GitHub Desktop.
Using the SoftLayer API via XML-RPC with Python
import xmlrpclib
from pprint import pprint
"""
A simple workout for the SoftLayer API as exposed via XML-RPC
"""
# TODO: Make this object-based instead of dictionary-based
# TODO: Read authentication information from a secure location
# TODO: Demonstrate how to call a method that requires a parameter
# Get this information from https://manage.softlayer.com/Administrative/apiKeychain
username = ''
api_key = ''
endpoint_base = 'http://api.service.softlayer.com/xmlrpc/v3/SoftLayer_'
services = { 'account': 'Account',
'hardware': 'Hardware',
}
headers_base = { 'headers': {} }
#
# Header construction
#
def make_auth_header(username, api_key):
header = {
'authenticate' : {
'username': username,
'apiKey': api_key
}
}
return header
def make_hw_init_header(id):
header = {
'SoftLayer_HardwareInitParameters': {
'id': id
}
}
return header
def make_obj_mask_header():
header = {
'SoftLayer_HardwareObjectMask': {
'mask': {
'datacenter': '',
'operatingSystem': ''
}
}
}
return header
def add_header(current_header, new_header):
current_header['headers'].update(new_header)
return current_header
#
# Service acquisition
#
def make_endpoint(service_name):
return endpoint_base + service_name
def get_service(service):
service_endpoint = make_endpoint(services[service])
return xmlrpclib.ServerProxy(service_endpoint)
#
# Using the Account and Hardware services
#
def get_server_list():
account_sv = get_service('account')
auth_header = make_auth_header(username, api_key)
headers = add_header(headers_base, auth_header)
server_list = account_sv.getHardware(headers)
return server_list
def get_dc_and_os(server_id):
"""
The SL API employs an Object Mask to reduce
the number of API calls necessary.
"""
hw_sv = get_service('hardware')
auth_header = make_auth_header(username, api_key)
hw_init_header = make_hw_init_header(server_id)
obj_mask_header = make_obj_mask_header()
headers = add_header(headers_base, auth_header)
headers = add_header(headers, hw_init_header)
headers = add_header(headers, obj_mask_header)
dc_and_os = hw_sv.getObject(headers)
return dc_and_os
if __name__ == '__main__':
# Get a list of all servers owned by an account
server_list = get_server_list()
# Get the data center and operating system for each server
server_data = {}
for server in server_list:
server_id = server['id']
dc_and_os = get_dc_and_os(server_id)
server_data[server_id] = dc_and_os
pprint(server_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment