Linux Labs

Automation: Git and Ansible / Stage 7 of 8

Roles, variables and secrets

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 6 · on a machine · 7 min

Whose value wins

One variable can be set in several places. The order decides which value the template gets.

Variables of machines and groups go into directories next to the inventory: group_vars/web.yml is for all machines of the web group, host_vars/app1.yml is for the single machine app1. Ansible reads these files by itself; the playbook does not name them. ansible-inventory --host app1 shows what the machine got from the inventory and these directories.

When a variable is set in several places, the value comes from the one lower in the table: each row overrides the rows above it.

Where it is set For whom
a role's defaults/main.yml every play with this role
group_vars/<group>.yml the machines of the group
host_vars/<machine>.yml one machine
a play's vars the tasks of this play
-e name=value one run

-e beats everything, but it works only in its own run: the next run without it brings the previous value back. There are more places for variables; the full order is in the Wiki.

Exercise · do it

Give docs its own phone

In ~/ansible-lab the three sites share the web group's phone from group_vars/web.yml. Your colleague wanted to give docs its own line 8-800-555-04-04 and wrote it into host_vars/app1.yml — now this number is on all three sites. Make docs show 8-800-555-04-04 and shop and blog show the group's phone. Run all three playbooks.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Give shop and blog the group's phone back not done yet
  • Keep docs on its own phone not done yet

Step goals

0 of 2
  • Give shop and blog the group's phone back — not done yet
  • Keep docs on its own phone — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Give shop and blog the group's phone back — not done yet
  • Keep docs on its own phone — not done yet
Loading…