Created
April 23, 2012 19:32
-
-
Save leetrout/2473280 to your computer and use it in GitHub Desktop.
Rackspace CloudServers tools for Fabric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Rackspace CloudServers tools for Fabric""" | |
| import os | |
| from cloudservers import CloudServers | |
| from fabric.api import task, prompt | |
| from fabric.contrib.console import confirm | |
| RS_USER = os.environ.get('CLOUD_SERVERS_USERNAME') | |
| RS_API_KEY = os.environ.get('CLOUD_SERVERS_API_KEY') | |
| cloudservers = None | |
| def _ensure_cs(): | |
| """Ensures a Rackspace CloudServers instance is attempted.""" | |
| global cloudservers | |
| if cloudservers is None: | |
| print("Authenticating with Rackspace...") | |
| cloudservers = CloudServers(RS_USER, RS_API_KEY) | |
| return cloudservers | |
| def _get_as_list_and_choices(iter, ident): | |
| """Returns a list of items and choice text for the given iterable""" | |
| choices = ['%s. %s' % (idx, name) for idx, name in enumerate(iter)] | |
| choice_txt = 'Available %s list:\n' % ident | |
| choice_txt += '\n'.join(choices) | |
| choice_txt += '\nPlease select a(n) %s (by number):' % ident | |
| return iter, choice_txt | |
| def _name_is_unique(name): | |
| """Fabric validation method to determine if the given server name is | |
| unique. | |
| """ | |
| cs = _ensure_cs() | |
| print('Validating name "%s" with Rackspace...' % name) | |
| servers = cs.servers.list() | |
| names = [svr.name.lower() for svr in servers] | |
| if name.lower() in names: | |
| exc_txt = 'Server already exists with name "%s". Existing Servers:\n' % name | |
| exc_txt += "\n".join(names) | |
| raise Exception(exc_txt) | |
| return name | |
| @task | |
| def create_server(): | |
| cs = _ensure_cs() | |
| print("Retreving images...") | |
| images, img_choices = _get_as_list_and_choices(cs.images.list(), 'image') | |
| img_idx = int(prompt(img_choices, validate=r'\d+')) | |
| image = images[img_idx] | |
| print("Retreving flavors...") | |
| flavors, flv_choices = _get_as_list_and_choices(cs.flavors.list(), 'flavor') | |
| flv_idx = int(prompt(flv_choices, validate=r'\d+')) | |
| flavor = flavors[flv_idx] | |
| name = prompt('Server name:', validate=_name_is_unique) | |
| bld_txt = "Create server \"%s\" (%s, %s)?" % (name, image, flavor) | |
| if confirm(bld_txt): | |
| cs.servers.create(name, image, flavor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment