Skip to content

Instantly share code, notes, and snippets.

@yujiod

yujiod/mackerel.py

Last active Aug 29, 2015
Embed
What would you like to do?
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