Search code examples
ansibleansible-inventory

Is there a way in ansible to access variables with multiple keys like in hosts.yml in other file?


In hosts.yml we can declare variables like that:

group1_hosts:
  hosts:
    host1:
    host2:
      var1: var1val1
      var2: var2val2

Then we have this variable available on two hosts - multiple keys can have same values.

Is this possible to declare variables in group_vars/all.yml in similar way:

variables:
  host1:
  host2:
    var1: var1val1
  host3:
  host4:
    var1: var1val2

and then access them like - {{ variables[inventory_hostname].var1 }}

If the idea is not clear - I would like to avoid setting two variables for every environment hosts in many files. Instead I would like to have it declared in group_vars so if some of hosts have same configuration I doesn't have to edit multiple files.

And I assume thats possible to wrote it like that:

variables:
  host1:
    var1: var1val1
  host2:
    var1: var1val1
  host3:
    var1: var1val2
  host4:
    var1: var1val2

but thats not a convenient solution as well.

Is there a way in ansible to store variables in such way?


Solution

  • Q: "Avoid setting two variables for every environment host in many files. Instead, I would like to have it declared in group_vars so if some of the hosts have the same configuration I don't have to edit multiple files."

    A: For example, given the inventory

    shell> cat hosts
    [group1_hosts]
    host1
    host2
    

    put the variables into the group_vars/group1_hosts.yml

    shell> cat group_vars/group1_hosts.yml
    var1: var1val1
    var2: var2val2
    

    Then the playbook

    - hosts: group1_hosts
      tasks:
        - debug:
            var: var1
    

    gives

    ok: [host1] => 
      var1: var1val1
    ok: [host2] => 
      var1: var1val1
    

    See Variable precedence: Where should I put a variable? how to override the group_vars.