- While working with Ansible
you will also encounter the so-called magic variables.
Let me give you a quick overview.
So a magic variable is a special reserved system variables.
There's a couple of them, like hostvars,
which prints all the variables assigned to a host,
or groups, which is about all host groups,
or group_names, which prints all names of the host groups.
Or inventory_hostname,
that is the host name as defined in inventory.
Inventory_hostname_short, the short alternative.
And there's a couple more, which you won't see that often.
Now, you should know that these metric variables
are reserved.
You cannot redefine them yourself.
They have the highest possible priority.
Funny story, first time I encountered magic variables
was while working with the playbook to create users.
And of course I wanted to define the variable groups.
That's not going to work
because of the magic variable groups.
Can you just imagine that all my users
were becoming a member of the groups, as in the host groups?
That didn't make sense.
Well, metric variables explain everything.
So, how do you use them?
Well, hostvars can be used to address facts
or inventory variables from other hosts,
as in hostvars ansible 2 ansible facts distribution.
That's something that you can put in a playbook
to point to a variable of another host
in a specific playbook.
Groups can be used to list all hosts in an inventory group.
As in the template, conditional structure
for host in group web servers.
We'll see a better example of this
while discovering templates in all of the upcoming lessons.
Group_names has all the inventory groups a host is in.
So that is very convenient
because you can use a conditional, like here,
the conditional structure, as you can see it in a template:
if 'web servers' in group_names.
That's going to discover if a host is a member
of the group web servers.
Now inventory_hostname or inventory_hostname_short
can be used to address a host
as alternative to ansible_hostname
when fact-gathering is disabled.
So at least it allows you to work with
hostnames anyway.
And that's what you need to know about magic variable.
Let's continue.