How to merge inventories from other ansible projects?

I have existing two ansible projects:

proj1/inventory/host.yml
all:
vars:…
hosts: …
children: …

proj2/inventory/host.yml
all:
vars:…
hosts: …
children: …

I want to create a new ansible project, whose inventory is the automatic merging of the existing two, which should be something like:

all:
children:
proj1:
vars: … # from proj1’s all.vars
hosts: … # from proj1’s all.hosts
children: … # from proj1’s all.children
proj2:
vars: … # from proj2’s all.vars
hosts: … # from proj2’s all.hosts
children: … # from proj2’s all.children

Is this something easily achievable in ansible?

Thanks in advance.

You can just reference both when calling ansible-playbook:

ansible-playbook -i /inv1 -i /inv2 play.yml

Or If you want a static copy:

ansible-inventory -i /inv1 -i /inv2 --exports --list --yaml > newmerged.yml

Thanks for the quick reply. However I don’t think it works.

Maybe I was not clear. Here is a small test case to demonstrate the issue:

proj1/inventory/hosts.yml
all:
vars:
bar: from 1 all
hosts:
example1.com:

proj2/inventory/hosts.yml
all:
vars:
bar: from 2 all
hosts:
example2.com:

proj3/playbook.yml

  • hosts: example1.com
    connection: local
    tasks:
  • debug:
    var: bar

And run the playbook with
ansible-playbook -i …/proj1/inventory -i …/proj2/inventory playbook.yml

Apparently proj2’s all.vars will override proj1’s, so bar shows “from 2 all”, which is not what I want.

I want proj3’s inventory to have two groups, group1 and group2, where proj1’s all.vars become group1’s group vars, ditto for proj2, so all.vars don’t get overridden. In the test case, I’d like bar to be “from 1 all”

Is this something possible to do?

nothing will autogenerate discrete groups that way, conflicts will be
resolved by overwriting.
You'll have to script something that processes each inventory and
rewrites the entries to what you want.

conflicts will be resolved by overwriting precedence.

Walter

Guess I’ll use a script to generate the inventory, thanks for the heads up.