0
votes

I would like to be able to reference the direct parent of an ansible host as a variable.

Take the following example inventory:

[resourcegroup1]
host1
host2

[resourcegroup2]
host3
host4

[application:children]
[resourcegroup1]

[database:children]
[resourcegroup2]

[environoments:children]
[application]
[database]

[enivronoments]
dev
staging
prod

I would like to run a looping task in a play which can reference a hosts parent. Example:

tasks:
- name: Start Datanbase Servers
  with_items: "{{ groups['database'] }}"   
  azure_rm_virtualmachine:
    name: "{{ item }}"
    resource_group: "{{ item.parent }}"
    started: yes
    allocated: yes

{{ item }} would iterate through the values of "host3" and "host4" while I am looking for what I could put in place of {{ item.parent }} that would be the hosts direct parent, in this case: "resourcegroup2".

Is there any way to reference the hierarchy of an inventory?

1
Hi @Drew, It's quite possible the functionality you're interested in may not be built into Ansible. What are you trying to accomplish by knowing the hierarchy of an inventory? Maybe there's another approach to what you're trying to do.Michael Ababio

1 Answers

0
votes

After doing some quick research, it appears Ansible doesn't have that sort of functionality builtin.

According to the tickets opened in Ansible Github repo, it sounds like people were interested in this feature, but was never developed. Probably because of the battle between usefulness & complexity.

Ansible Tix

Ansible Tix

Here are some snippets from the above links:

It would be nice to have a way of recreating inventory group hierarchy inside i.e. Jinja2 template.

@kinvaris We have dynamic inventories for this. You could just write a small dynamic inventory script, and have it translate. I don't see why this is a necessary addition, it only complicates the tools even more.

If you just want a list of groups associated with a host, but don't care about hierarchical structure:

'{{hostvars["host1"]}}'

You'll get an list like this:

"groups": {
            "all": [
                "host"
            ],
            "child": [
                "host1"
            ],
            "parent": [
                "host1"
            ],
            "ungrouped": []
        },