LOGBOOK

HELP

1 / 39
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

Why does Ansible use variables, and what rules does a variable name have to follow?

Answer

Variables store values once and reuse them across a project, so playbooks are easier to write and maintain, less error-prone, and adaptable to different environments. A name must start with a letter and contain only letters, digits and underscores.

Without variables, the same value (a package name, a path, a port) is typed into every task that needs it. Change it and you have to find every copy; miss one and the hosts drift apart. With a variable, the value lives in one place and every task refers to it, so one edit changes them all. The same playbook can also run against test and production with different values, because only the variables differ, not the tasks.

Typical things to put in variables:

  • users to create
  • packages to install
  • services to restart
  • files to remove
  • archives to download
Name Valid? Why
web_package yes letters and an underscore
port80 yes digits are fine after the first letter
80port no starts with a digit
web-package no a hyphen is not allowed (Jinja2 would read it as a minus)
web package no no spaces

Go deeper:

or press any other key

Question

Where can a variable be defined in Ansible, and which definition wins if the same name is set in several places?

Answer

From lowest to highest priority: group variables in the inventory, group_vars files, host variables in the inventory, host_vars files, gathered facts, play variables (vars, vars_files), task variables, and extra variables on the command line. The higher one overrides; the rule of thumb is "more specific beats more general".

Variable precedence ladder from inventory group variables at the bottom to extra variables at the top

* Higher rungs override lower ones; extra vars (-e) always win. *

The ladder follows two ideas:

  1. Narrow beats broad. A value for one host is more specific than a value for a whole group, and a value for one task is more specific than one for the whole play. So host variables beat group variables, and task variables beat play variables.
  2. Closer to the run beats further away. The inventory describes the environment; the playbook describes this job; the command line describes this one run. That is why --extra-vars / -e overrides everything: it is the operator saying "for this run, use this value".

In short: inventory variables < playbook variables < extra variables.

Precedence can be used on purpose (a group default that one special host overrides). Where you don't need that, give variables unique names, so there's never a question of which definition wins.

Go deeper:

or press any other key