Can an Ansible inventory include another?
Solution 1:
To start with, your example inventory in your question does not respect the schema for yaml ansible inventory and will be declined parsing.
Now to answer your question, you can simply use several inventories at once. Here is a simple example:
I created 3 yaml inventory files:
-
inventories/hosts.yml
--- group1: hosts: host1: host2:
-
inventories/otherhosts.yml
--- group2: hosts: hostA: hostB:
- and finally
inventories/shared.yml
--- sharedservers: hosts: host3: host4:
From there, it is fairly easy to address all needed hosts. The example below use ansible-inventory
for a better output, but the -i
option and target selection is the same whith ansible
and ansible-playbook
- Address all hosts in all inventory files inside inventory directory:
This is equivalent to calling each yaml files in a seperate$ ansible-inventory -i inventories/ all --graph @all: |--@group1: | |--host1 | |--host2 |--@group2: | |--hostA | |--hostB |--@sharedservers: | |--host3 | |--host4 |--@ungrouped:
-i
option in this caseansible-inventory -i inventories/hosts.yml \ -i inventories/otherhosts.yml -i inventories/shared.yml \ all --graph
- Address only specific inventories
$ ansible-inventory -i inventories/hosts.yml \ -i inventories/shared.yml all --graph @all: |--@group1: | |--host1 | |--host2 |--@sharedservers: | |--host3 | |--host4 |--@ungrouped: $ ansible-inventory -i inventories/otherhosts.yml \ -i inventories/shared.yml all --graph @all: |--@group2: | |--hostA | |--hostB |--@sharedservers: | |--host3 | |--host4 |--@ungrouped:
Solution 2:
You could take advantage of what is already there in Ansible:
Using inventory directories, you can specify a folder where all your inventory files are located and they will be included one by one in alphabetical ordering.
-
You can use multiple inventory sources using either:
- multiple
-i
options in the command line - the
ANSIBLE_INVENTORY
environment variable and supply a comma separated list of inventory paths (either directories or files) - the
inventory
option inansible.cfg
to do the same as above.
- multiple
See the docs.
I doubt that with the above you will not be able to cover your needs. It is better to modify your wrapper scripts and your project's file structure a bit than hack your way into pyyaml and ansible. /intro_inventory.html?highlight=inventory directory#using-multiple-inventory-sources) for more information.