Lesson 5 of 13 · 24m
Variables, Facts, and the 22-Level Precedence Maze
Where variables live, which precedence rungs actually bite, and why ansible_facts['x'] is the spelling that survives 2.24.
A teammate once burned a day on "the deploy used the staging API URL in prod." The value existed in five places: role defaults, group_vars, host_vars, a vars: block on the play, and an -e on the Jenkins job nobody remembered writing. The playbook wasn't broken. The team just didn't share a model of which variable wins — and in Ansible, the winner is decided by a precedence ladder that is 22 rungs deep and only three of them matter in practice.
Facts first: what the host reports
gather_facts: true (the default) runs the setup module and populates ansible_facts — distribution, kernel, every NIC, every mount, memory totals, virtualization platform, all of it, per host, gathered fresh each play.
- name: What I'd actually template with
ansible.builtin.debug:
msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }} on {{ ansible_facts['default_ipv4']['address'] }}"Write ansible_facts['distribution'], not ansible_distribution. The flat, ansible_*-prefixed spellings still work because INJECT_FACTS_AS_VARS defaults true — but that default is deprecated in ansible-core 2.20 and flips to false in 2.24. Every new playbook that uses ansible_facts[...] is one fewer deprecation warning you'll triage later.
Facts cost a setup run per host per play. On a big fleet that's real time, so plays that don't touch facts set gather_facts: false, and fact caching (gathering = smart plus fact_caching = jsonfile or redis) makes "already collected" a durable answer instead of a per-run tax.
The precedence ladder, compressed to the rungs that bite
Weakest to strongest:
- Role
defaults/main.yml— the contract layer; every value is a public, overridable knob. - Inventory —
group_vars/all, then more-specific group_vars, thenhost_vars. - Gathered facts — the host's reported reality.
- Play-level —
vars:,vars_files:,vars_prompt:. - Role
vars/main.yml, block and taskvars:— high precedence; for internal constants, not knobs. set_fact/registered results — minted mid-run, sticky for the host.-eextra vars — wins everything. Always. Including the things you forgot existed.
The operational mnemonic: defaults are for libraries, group/host vars are for environment, -e is for emergencies and CI parameters. A "configurable" value hiding in vars/main.yml silently outranks the operator's group_vars — that's the most common role bug in the wild, and it fails quietly: the play runs green, the port stays 8080.
register and set_fact: variables born during the run
- name: Get installed version
ansible.builtin.command: nginx -v
register: nginx_version
changed_when: false
failed_when: nginx_version.rc not in [0, 1] # nginx -v prints to stderr, rc 0
- name: Keep it for later plays
ansible.builtin.set_fact:
deployed_nginx: "{{ nginx_version.stderr }}"register captures one task's entire result blob — stdout, stderr, rc, changed, plus module-specific fields — visible downstream. set_fact goes further: it mints a genuine host variable that survives across tasks and subsequent plays for the rest of the run. The classic use is "the cloud module just handed me an instance object; extract its private IP once, use it for the next forty tasks."
Magic variables worth memorizing
inventory_hostname— the name the inventory knows, which may not be DNS's opinion.groups['webservers']— every host in the group; the template driver's peer list.hostvars['db01']['ansible_facts']— another host's facts. This is how every web node learns the DB's IP. The trap:hostvarsonly holds facts for hosts the run has actually set up or cached — template fordb01before any play has touched it and you'll meetansible_factsundefined in a wall of Jinja.play_hosts,ansible_play_batch— the full host list vs. the currentserialslice. Batch-aware logic needs the second one.
YAML's own trap
A scalar that begins with {{ must be quoted — port: "{{ app_port }}" — or YAML parses it as a flow mapping and the playbook fails to load with an error that points nowhere near the variable. And a string "false" arriving via -e is truthy; run it through | bool before trusting it in a when:.
Field notes
ansible.builtin.debug: var=suspicious_variableprints the resolved structure — cleaner thanmsg:when the value is a dict.- When you genuinely cannot find a value's source,
grep -r varname inventories/ roles/ playbooks/plus-e's command line is the whole search space. There is no sixth place. - Precedence questions are design smells. If a value needs five homes, the answer is deleting four of them, not memorizing the ladder.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
AWS Emulator Puts AWS on Your Laptop. Keep Your IAM Tests Off It.
AWS released AWS Emulator on November 11, a free local server that answers AWS API calls on 127.0.0.1 with per-run keys and fresh certificates.