Pass dynamic inventory as json not as file

Hello

First question:

Is there any possibility to pass dynamic inventory as a pure json structure?

I have got a small app that is written in python and flask, that listen for some data (finally it is in json format) from other system. Based on this data I prepare _meta structure like below:

‘hosts’: {

‘hosts’: [‘host001’, ‘host001’],

‘vars’: {

‘var01’: “value01”,
}

},
‘_meta’: {

‘hostvars’: {

‘host001’: { ‘var001’ : “value02” },
‘host002’: { ‘var002’: “value03” }
}

}

Using this structure I’m creating inventory script that returns above code. Than based on ansible Python API documentation I run ansible task using some playbook and inventory script.

In above documentation you can find: “# create inventory, use path to host config file as source or hosts in a comma separated string inventory = InventoryManager(loader=loader, sources=sources)”

And now is my question: is there any easy way to pass above inventory not as a “/path/to/inventory_script” but as a pure json structure?

I have read about ansible-runner project which can be simpler implementation of creating and runnning ansible task (instead of pure API) but there I still have to pass “/path/to/file” as inventory.

Now I’m reading about writing my own plugin for ansible but maybe there is an easier way to do what I mentioned above. Maybe you have some other suggestions.

Best Regards
Filip

You can feed JSON to the YAML inventory plugin (since JSON is mostly
a subset of YAML), but it must follow the structure it uses, which is
different than the inventory script.

Hi,

Thank you for your reply.

I can create this structure in YAML format, but what i really want to achieve is pass this structure as json/yaml variable. As I read this YAML plugin still require to save structure to file and than pass it to ansible API (if I’m wrong please correct me).
To be more precise (using example from: ansible Python API) I would like to create inventory variable like below;

create inventory, use path to host config file as source or hosts in a comma separated string

inventory = InventoryManager(loader=loader, sources=sources)

where source would be like:
source = {

‘hosts’: {

‘hosts’: [‘host001’, ‘host001’],

‘vars’: {

‘var01’: “value01”,
}

},
‘_meta’: {

‘hostvars’: {

‘host001’: { ‘var001’ : “value02” },
‘host002’: { ‘var002’: “value03” }
}

}
}

Here I use json format, but it can be any YAML formatted variable.

Best regards
Filip

You need create an inventory plugin that handles it, as of now i don't
know of any that exist that do what you want.

Thanks for your answer. I wanted to avoid writing my own plugin, but if there is no other options I will try this.

Best Regards
Filip