Chapter Five

Variables & Facts

Where a value comes from, which source wins the 22-level precedence fight, and how facts gathered live off each box every run feed ports, paths, and the templated app.env. set_fact, registered vars, magic variables for cross-host reads, fact caching, and the hygiene that keeps it all maintainable.

7 topics

Variables are where an Ansible project earns its keep or rots. The same {{ nginx_port }} can arrive from a role default, a group_vars file, a play vars:, a set_fact, or -e on the command line — and when two of those define it, a fixed 22-level precedence decides which value the template actually sees. Get this wrong and you spend an afternoon editing a file that never wins.

Facts are the other half: the OS, the IP, the memory, the disk layout that Ansible discovers by interrogating each box live at the start of every run. There is no state file, so Ansible never recalls what web1 looked like yesterday — it asks today, and the answer is the truth. This chapter takes the Larkspur web stack and feeds its ports, paths, and templated app.env from layered variables and from facts read off the machine in real time.

Topics in This Chapter

Topic 26
Defining Variables
Where a value can come from — play vars, role defaults and vars, group_vars/host_vars, and -e — and what shape it has. Scalars, lists, dicts, {{ }} referencing, scope, and what makes a variable name invalid.
ConceptVariables
Topic 27
Variable Precedence
The fixed 22-level hierarchy from role defaults at the floor to --extra-vars at the ceiling. The short ladder real conflicts actually hit, and how to debug a wrong value instead of guessing.
ConceptVariables
Topic 28
Facts and Gathering
Properties Ansible discovers live off each node every run — OS, IPs, memory, disks — landing in ansible_facts. gather_facts, gather_subset, and the setup module as an ad-hoc probe.
ConceptFacts
Topic 29
set_fact and Registered Variables
register captures a task's output, set_fact names a computed value for the rest of the run, and facts.d lets a node publish its own custom facts. Where each sits in precedence and when to reach for which.
FactsWorkflow
Topic 30
Magic Variables
Values Ansible sets automatically that describe the run — inventory_hostname, hostvars, groups, group_names, ansible_play_hosts. The cross-host read that lets a web host template the database's live IP.
ConceptVariables
Topic 31
Fact Caching
Persisting gathered facts in jsonfile or Redis so a targeted play can read a host that wasn't in it. gathering = smart, the freshness-vs-speed TTL, and why a stale cache costs speed but never correctness.
FactsPerformance
Topic 32
Variable Hygiene
One flat namespace per host means a bare port collides across roles. Role-name prefixing, defaults as public API versus vars as private, the late-binding trap, and debugging when files lie.
ConceptWorkflow