Skip to content

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:

  1. Role defaults/main.yml — the contract layer; every value is a public, overridable knob.
  2. Inventory — group_vars/all, then more-specific group_vars, then host_vars.
  3. Gathered facts — the host's reported reality.
  4. Play-level — vars:, vars_files:, vars_prompt:.
  5. Role vars/main.yml, block and task vars: — high precedence; for internal constants, not knobs.
  6. set_fact / registered results — minted mid-run, sticky for the host.
  7. -e extra 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: hostvars only holds facts for hosts the run has actually set up or cached — template for db01 before any play has touched it and you'll meet ansible_facts undefined in a wall of Jinja.
  • play_hosts, ansible_play_batch — the full host list vs. the current serial slice. 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_variable prints the resolved structure — cleaner than msg: 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.