Created
August 13, 2014 13:08
-
-
Save cchurch/6203028e8c46c42a9aa2 to your computer and use it in GitHub Desktop.
Sample executable inventory script to read an INI and output in JSON for Ansible.
This file contains 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
# Sample hosts file in INI format. | |
[webservers] | |
web1.example.com ansible_ssh_host=w1.example.net | |
web2.example.com ansible_ssh_port=1022 | |
[webservers:vars] # Comment on a section | |
webvar=blah # Comment on an option | |
[dbservers] | |
db1.example.com | |
db2.example.com | |
[dbservers:vars] | |
dbvar=ugh | |
[servers:children] | |
webservers | |
dbservers | |
[servers:vars] | |
varb=B | |
[all:vars] | |
vara=A |
This file contains 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
#!/usr/bin/env python | |
import json | |
import shlex | |
inv = {'_meta': {'hostvars': {}}} | |
section = group_name = 'all' | |
for line in open('hosts'): | |
line = line.split('#')[0].strip() | |
if not line: | |
continue | |
if line.startswith('[') and line.endswith(']'): | |
section = line[1:-1].strip() | |
group_name = section.split(':')[0] | |
else: | |
group_dict = inv.setdefault(group_name, {}) | |
tokens = shlex.split(line) | |
if section.endswith(':vars'): | |
group_vars = group_dict.setdefault('vars', {}) | |
group_vars.update(dict([t.split('=', 1) for t in tokens])) | |
elif section.endswith(':children'): | |
group_children = group_dict.setdefault('children', []) | |
group_children.append(line) | |
else: | |
group_hosts = group_dict.setdefault('hosts', []) | |
group_hosts.append(tokens[0]) | |
host_vars = inv['_meta']['hostvars'].setdefault(tokens[0], {}) | |
host_vars.update(dict([t.split('=', 1) for t in tokens[1:]])) | |
print json.dumps(inv, indent=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment