Ansible doesn't return correct group_vars, why?

107 views Asked by At

deploy.yaml

---
- name: test
  hosts: host_a
  tasks:
    - name: debug
      debug:
        var: demo

inventory

[host_a]
localhost

[host_a:vars]
demo=aaa

[host_b]
localhost

[host_b:vars]
demo=bbb

When I run the playbook, I want the variable demo to return aaa, but it returns bbb.

Why?

1

There are 1 answers

1
techraf On

Ansible doesn't return correct group_vars, why?

Because a variable defined in inventory is treated as a fact, and a fact is bound to a host in Ansible. As you define only one host, named localhost, the first value gets overwritten.

Confirm with:

[host_a]
127.0.0.1

[host_a:vars]
demo=aaa

[host_b]
127.0.0.2

[host_b:vars]
demo=bbb

or

[host_a]
localhost1 ansible_ssh_host=localhost

[host_a:vars]
demo=aaa

[host_b]
localhost2 ansible_ssh_host=localhost

[host_b:vars]
demo=bbb