Skip to content

Instantly share code, notes, and snippets.

@yujiod
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yujiod/1587128075bc74009d32 to your computer and use it in GitHub Desktop.
Save yujiod/1587128075bc74009d32 to your computer and use it in GitHub Desktop.
Ansible Dynamic Inventory for Mackerel
#!/usr/bin/python
import urllib
import urllib2
import sys
try:
import json
except ImportError:
import simplejson as json
apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
service = 'My Service'
networkInterface = 'eth0'
def getGroupList():
hosts = getHosts()
print json.dumps(hosts)
def getHostInfo(hostname):
hosts = getHosts(hostname)
print json.dumps(hosts['_meta']['hostvars'][hostname])
def getHosts(hostname=None):
params = { 'service': service }
if hostname != None:
params['name'] = hostname
url = 'https://mackerel.io/api/v0/hosts.json?' + urllib.urlencode(params)
headers = { 'X-Api-Key': apiKey }
request = urllib2.Request(url, None, headers)
response = urllib2.urlopen(request)
hosts = json.loads(response.read())
inventories = {
'production': { 'hosts': [], 'children': [] },
'_meta': { 'hostvars': {} },
}
for host in hosts['hosts']:
ipAddress = None
for interface in host['interfaces']:
if interface['name'] == networkInterface:
ipAddress = interface['ipAddress']
break
if ipAddress == None:
continue
for serviceName, roles in host['roles'].iteritems():
for role in roles:
if role not in inventories:
inventories[role] = { 'hosts': [] }
inventories[role]['hosts'].append(host['name'])
inventories['_meta']['hostvars'][host['name']] = {
'ansible_ssh_host': ipAddress,
'ansible_ssh_port': '22',
}
if role not in inventories['production']['children']:
inventories['production']['children'].append(role)
return inventories
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
getGroupList()
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
getHostInfo(sys.argv[2])
else:
print "Usage: %s --list or --host <hostname>" % sys.argv[0]
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment