Skip to content

Instantly share code, notes, and snippets.

@willthames
Created September 1, 2016 23:20
Show Gist options
  • Save willthames/a823d102290960bff4e9c40062c56b5f to your computer and use it in GitHub Desktop.
Save willthames/a823d102290960bff4e9c40062c56b5f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import collections
import json
import os
import sys
''' location returns the location portion of the hostname '''
def location(host):
return host.split('.')[-3]
''' list_hosts returns a dictionary of the hosts in each location
and also sets the geo_location of each host as a variable '''
def list_hosts():
geos = collections.defaultdict(list)
directory = os.path.dirname(__file__) or '.'
for filename in [os.path.join(directory, item)
for item in os.listdir(directory)
if '.' not in item and
os.path.isfile(os.path.join(directory, item))]:
with open(filename) as fh:
for line in fh:
if '.redhat.com' in line:
host = line.strip()
geo = location(line)
if host not in geos[geo] and not host.startswith('#'):
geos[geo].append(host)
# Tuning for Ansible 1.3 onwards
# See http://docs.ansible.com/developing_inventory.html
hostvars = dict()
for geo, hosts in geos.items():
for host in hosts:
hostvars[host] = {'geo_location': geo}
geos['_meta'] = dict(hostvars=hostvars)
return geos
''' list_host returns a dictionary containing the geolocation of the host '''
def list_host(hostname):
return {'geo_location': location(hostname)}
def main(args):
if len(args) > 1 and args[1] == '--list':
print json.dumps(list_hosts())
return 0
elif len(args) > 2 and args[1] == '--host':
print json.dumps(list_host(args[2]))
return 0
else:
print '%s --list|--host <hostname>' % args[0]
return 1
if __name__ == '__main__':
sys.exit(main(sys.argv))
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment