Pass dynamic JSON/YAML inventory to ansible CLI

Hi All,

while trying, and so far not very successfully, to work with the (overly verbose) Ansible 2 programmatic API, I came to think of another possible solution to my problem, but am looking for tips on how to put it into action.
The problem: I have a python REST server which accepts host registrations. From these I’m able to generate a JSON/YAML inventory blob, that I’d like to pass simply to the ansible-playbook command line command spun up in a seperate thread. I do not want to write the inventory to a local file.

In other words, invoke ansible CLI from my python script, but poassing a dynamically generated inventory blob.

Playing around with all kinds of “ansible-playbook -i … ” redirects was so far unsucessful. Any pointers/examples of something like this?

Cheers,
W.

You are going to need an actual file. There really isn’t a way to just pass an inventory blob into ansible, that doesn’t exist as a file.

I’ve done it with the ansible python API, but it was a bit complex, and potentially very fragile as the API was not designed for this.

I hit enter too early, my other recommendation was an inventory script, that wouldn’t have to have anything hard coded, and could pull from the same database that your “REST server” utilizes. For documentation on dynamic inventories see:

http://docs.ansible.com/ansible/dev_guide/developing_inventory.html

Ok thanks. Indeed I’ve resorted to writing the inventory and host parameters to a tmp file, off a jinja2 template, and using the ansible -i option to read from it. Still it would be a nice enhancement for Ansible to support such “piped” inventories, as the Ansible API is way too cumbersome to use (passing all those config params is a nightmare in 2.0+).

Rough working code is:

inventory_template = jinja2.Template(inventory)
rendered_inventory = inventory_template.render({
‘host’: “centos2”
})

Create a temporary file and write the template string to it

hosts_inv = NamedTemporaryFile(delete=False, bufsize=0)
hosts_inv.write(rendered_inventory)

cmd = "ansible-playbook " + playbook +
" -i " + hosts_inv.name
" -e " + extra_params

if debug:
cmd += " -vvv"
print(“Ansible command: %s” % cmd)
with hosts_inv:
try:
ret = call(cmd, shell=True)
except Exception as e:
print “ERROR: [%s]: could not execute [%s]” % (cmd, e.errno)
if not ret:
print(“Command ‘%s’ executed successfully” % cmd)
else:
print “ERROR: [%s]: failed in execution not execute [%s]” % (cmd, ret)