Variable precedence in a group hierarchy

68 views
Skip to first unread message

Sandra Parsick

unread,
Apr 17, 2015, 11:31:47 AM4/17/15
to ansible...@googlegroups.com
Hello list,

I need to understand following variable precedence problem.
I have an inventory file with following group hierarchy:
# inventory file
host1
host2

[group1]
host1
host2

[group11:children]
group1

[group12:children]
group1

In the group_var files of group group11 and group12, a variable var is defined with different value:
# content of group_vars/group11
var: "group11"

# content of group_vars/group12
var: "group12"

Furthermore, I have two playbooks that evaluate the variable var . One playbook is for the host group group11 and the second playbook is for group12

#content of playbook site-group11.yml
- hosts: group11
  tasks:
    - debug: var=var

#content of playbook site-group12.yml
- hosts: group12
  tasks:
    - debug: var=var


When I run both playbooks, I get the following output from both:

< TASK: debug var=var >
 ---------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


ok: [host1] => {
    "var": {
        "var": "group12"
    }
}
ok: [host2] => {
    "var": {
        "var": "group12"
    }
}

This output is ok for the playbook site-group12.yml. But my expectation is that the variable var has the value group11 in playbook site-group11.yml .

So my question, why my expectation is wrong?

Best regards,

Sandra

Serge van Ginderachter

unread,
Apr 17, 2015, 11:43:00 AM4/17/15
to ansible...@googlegroups.com

On 17 April 2015 at 17:31, Sandra Parsick <sandra....@googlemail.com> wrote:
So my question, why my expectation is wrong?


​yes, it's a feature, not a bug :)
Io just answered the same question on https://github.com/ansible/ansible/issues/10755, so copy pasting my answer:

This is a feature and not a bug, and has been asked several times yet here and on the list. You are trying to use a way to define things that just isn't the way ansible dpes things.

Ansible only uses variables on the host level. The inventory only returns variables after they are calculated/inherited down top that host level.

When you target a play to a particular group, that gets calculated down to a list of hosts. Whether you call groupA or groupB here, it results in the same host. And that hosts only has one particular value for myvar, which happens to be groupB because thats the last one bing parsed.

To quote the docs:

Remember: Child groups override parent groups, and hosts always override their groups.



    Serge

Sandra Parsick

unread,
Apr 17, 2015, 11:55:07 AM4/17/15
to ansible...@googlegroups.com
Serge, thanks for the fast clarification.
Reply all
Reply to author
Forward
0 new messages