Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script for converting Ansible dynamic inventory to static files. It's not perfect, but it'll get you 90% of the way there.
#!/usr/bin/env python
# Converts Ansible dynamic inventory sources to static files
# Input is received via stdin from the dynamic inventory file
# ex:
# --list |
import json
import os
import sys
import pyaml
def add_vars(_type, _id, variables):
assert _type == "group" or _type == "host"
dir_name = "./%s_vars" % _type
if not os.path.isdir(dir_name):
with open('%s/%s' % (dir_name, _id), 'a') as fh:
def add_host_vars(host, variables):
add_vars('host', host, variables)
def add_group_vars(group, variables):
add_vars('group', group, variables)
def main():
raw_json =
inventory = json.loads(raw_json)
inventory_filename = "./hosts"
with open(inventory_filename, 'a') as fh:
for group in inventory:
if group == "_meta":
for host, variables in inventory[group]["hostvars"].iteritems():
add_host_vars(host, variables)
if "vars" in inventory[group]:
add_group_vars(group, inventory[group]["vars"])
if "hosts" in inventory[group]:
fh.write("[%s]\n" % group)
for host in inventory[group]["hosts"]:
fh.write("%s\n" % host)
if "children" in inventory[group]:
fh.write("[%s:children]\n" % group)
for child in inventory[group]["children"]:
fh.write("%s\n" % child)
if __name__ == '__main__':

This comment has been minimized.

Copy link

@sudoer sudoer commented May 13, 2016

I ended up just dumping the inventory to a plain text file, and then making a 1-line executable bash script that just does cat inventory.txt. Since the script is executable, Ansible expects the inventory in dynamic JSON format, and it "just works". I suppose I'm just turning my plain text file into a "static dynamic inventory". Thanks for sharing this script, which was enough to get the creative juices flowing.

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