Eliminate the RAX_REGION environment variable; iterate through all regions available to an account and present servers in region groups; default to using server name to identify servers in groups; set ansible_ssh_host key for each server; utilize the _meta key to provide all the hostvars for each server; all grouping by web, db, sql, lb, app based on server name; pretty print JSON output for some human-readable inventory action

Add set_setting to alleviate requirement that ~/.pyrax.cfg exists

Add regions as a optional env var to narrow our inventory scope

Clean up
pull/4326/head
Paul Durivage 11 years ago committed by Paul Durivage
parent ccc607eaa5
commit 25c3bec6ef

@ -74,6 +74,7 @@ import sys
import re import re
import os import os
import argparse import argparse
import collections
try: try:
import json import json
@ -86,69 +87,123 @@ except ImportError:
print('pyrax required for this module') print('pyrax required for this module')
sys.exit(1) sys.exit(1)
# Setup the parser
parser = argparse.ArgumentParser(description='List active instances',
epilog='List by itself will list all the active \
instances. Listing a specific instance will show \
all the details about the instance.')
parser.add_argument('--list', action='store_true', default=True, def host(hostname):
help='List active servers') hostvars = {}
parser.add_argument('--host',
help='List details about the specific host (IP address)') for region in pyrax.regions:
# Connect to the region
args = parser.parse_args() cs = pyrax.connect_to_cloudservers(region=region)
for server in cs.servers.list():
# setup the auth if server.name == hostname:
try: keys = [key for key in vars(server) if key not in ('manager', '_info')]
creds_file = os.environ['RAX_CREDS_FILE'] for key in keys:
region = os.environ['RAX_REGION'] # Extract value
except KeyError, e: value = getattr(server, key)
sys.stderr.write('Unable to load %s\n' % e.message)
sys.exit(1) # Generate sanitized key
key = 'rax_' + (re.sub("[^A-Za-z0-9\-]", "_", key)
pyrax.set_setting('identity_type', 'rackspace') .lower()
.lstrip("_"))
try: hostvars[key] = value
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credential_file(os.path.expanduser(creds_file), # And finally, add an IP address
region=region) hostvars['ansible_ssh_host'] = server.accessIPv4
except Exception, e: print(json.dumps(hostvars, sort_keys=True, indent=4))
sys.stderr.write("%s: %s\n" % (e, e.message))
sys.exit(1)
def _list(region):
# Execute the right stuff groups = collections.defaultdict(list)
if not args.host: hostvars = collections.defaultdict(dict)
groups = {}
if region and region.upper() in pyrax.regions:
# Cycle on servers pyrax.regions = (region,)
for server in pyrax.cloudservers.list():
# Define group (or set to empty string) # Go through all the regions looking for servers
try: for region in pyrax.regions:
group = server.metadata['group'] # Connect to the region
except KeyError: cs = pyrax.connect_to_cloudservers(region=region)
group = 'undefined' for server in cs.servers.list():
# Create a group on region
# Create group if not exist and add the server groups[region].append(server.name)
groups.setdefault(group, []).append(server.accessIPv4)
# Anything we can discern from the hostname?
# Return server list try:
print(json.dumps(groups)) subdom = server.name.split('.')[0]
except IndexError:
pass
else:
for name in ('web', 'db', 'sql', 'lb', 'app'):
if name in subdom:
groups[name].append(server.name)
# Check if group metadata key in servers' metadata
try:
group = server.metadata['group']
except KeyError:
pass
else:
# Create group if not exist and add the server
groups[group].append(server.name)
# Add host metadata
keys = [key for key in vars(server) if key not in ('manager', '_info')]
for key in keys:
# Extract value
value = getattr(server, key)
# Generate sanitized key
key = 'rax_' + (re.sub("[^A-Za-z0-9\-]", "_", key)
.lower()
.lstrip('_'))
hostvars[server.name][key] = value
# And finally, add an IP address
hostvars[server.name]['ansible_ssh_host'] = server.accessIPv4
if hostvars:
groups['_meta'] = {'hostvars': hostvars}
print(json.dumps(groups, sort_keys=True, indent=4))
def parse_args():
parser = argparse.ArgumentParser(description='Ansible Rackspace Cloud '
'inventory module')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true',
help='List active servers')
group.add_argument('--host', help='List details about the specific host')
return parser.parse_args()
def setup():
try:
creds_file = os.environ['RAX_CREDS_FILE']
region = os.getenv('RAX_REGION')
except KeyError, e:
sys.stderr.write('Unable to load environment '
'variable %s\n' % e.message)
sys.exit(1)
pyrax.set_setting('identity_type', 'rackspace')
try:
pyrax.set_credential_file(os.path.expanduser(creds_file))
except Exception, e:
sys.stderr.write("%s: %s\n" % (e, e.message))
sys.exit(1)
return region
def main():
args = parse_args()
region = setup()
if args.list:
_list(region)
elif args.host:
host(args.host)
sys.exit(0) sys.exit(0)
# Get the deets for the instance asked for if __name__ == '__main__':
results = {} main()
# This should be only one, but loop anyway
for server in pyrax.cloudservers.list():
if server.accessIPv4 == args.host:
for key in [key for key in vars(server) if
key not in ('manager', '_info')]:
# Extract value
value = getattr(server, key)
# Generate sanitized key
key = 'rax_' + re.sub("[^A-Za-z0-9\-]", "_", key).lower()
results[key] = value
print(json.dumps(results))
sys.exit(0)

Loading…
Cancel
Save