Why does Ansible use variables, and what rules does a variable name have to follow?
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:
Using variables: creating valid variable names (official docs) — the naming rules and the keywords you must not use as names.
Ansible 101, Episode 5: handlers, environment vars and variables (Jeff Geerling) — variables in a running project.
Ansible (software) (Wikipedia) — background on the tool and its architecture.