Skip to content

Instantly share code, notes, and snippets.

@dopry
Last active August 29, 2015 14:05
Show Gist options
  • Save dopry/15cf368d7b6479b66a7a to your computer and use it in GitHub Desktop.
Save dopry/15cf368d7b6479b66a7a to your computer and use it in GitHub Desktop.
Ansible static inventory proxy for Vagrant, using Ansible's INI parser.
#!/usr/bin/env python
from ansible.inventory.ini import InventoryParser
import json
import os
file_path = os.path.dirname(os.path.realpath(__file__))
static_file = os.path.join(file_path, "hosts")
inv = { '_meta': { 'hostvars': {}}}
parser = InventoryParser(filename=static_file)
for group in parser.groups.values():
group_dict = inv.setdefault(group.name, {})
group_vars = group_dict.setdefault('vars', {})
group_children = group_dict.setdefault('children', [])
group_hosts = group_dict.setdefault('hosts', [])
for var in group.vars:
group_vars[var] = group.vars[var]
for child in group.child_groups:
group_children.append(child.name)
for host in group.hosts:
group_hosts.append(host.name)
host_vars = inv['_meta']['hostvars'].setdefault(host.name, {});
for var in host.vars:
host_vars[var] = host.vars[var]
print json.dumps(inv, indent=4)
@dopry
Copy link
Author

dopry commented Aug 14, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment