Search code examples
ansibleansible-inventory

Ansible Inventory file precedence


I've been reading through the vars precedence within Ansible and I'm not sure if the behavior I'm getting is by design or not. Here is my Ansible inventory;

---

all:
  children:
    we:
      children:
        workers:
          hosts:
            worker-we-vm1:
              order: 1
            worker-ew-vm2:
              order: 2
          vars:
            size: "Standard_B2s"
        controllers:
          hosts:
            controller-we-vm:
              order: 1
          vars:
            size: "Standard_B1s"
      vars:
        ip_prefix: "10.60"
    scus:
      children:
        workers:
          hosts:
            worker-scus-vm1:
              order: 1
            worker-scus-vm2:
              order: 2
          vars:
            size: "Standard_B2s"
      vars:
        ip_prefix: "10.61"
  vars:
    azure_profile: "test"

Now what I'd expect is that the we VMs (e.g. worker-we-vm1) would have ip_prefix set to 10.60 and the scus VMs (e.g. worker-scus-vm1) would have ip_prefix set to 10.61 when accessing hostvars. But they're not, all of the VMs have ip_prefix set to 10.60.

Can anyone please help with understanding why the vars precedence isn't working as expected? I've read https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html and it seems to contradict itself on how parent and same-level variables are handled.


Solution

  • Ansible host group namespace is flat, not hierarchical, so there is only a single workers group in your example.

    As you define the same variable for that group twice, only the last value is preserved.

    Split your workers group, for example, to workers_we and workers_scus (and use host patterns if that was the reason for the definition).