Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 29 ยท Variables and Logic

Variables, Facts and Precedence

Learn how Ansible variables work: vars, group_vars, host_vars, extra vars, gathered facts, set_fact, register, debug and the precedence rules that decide which value wins.

A playbook that hard-codes every port, path and user name works for exactly one server. Variables are how the same playbook serves a laptop lab, a staging group and a production fleet: the tasks stay the same, only the data changes. Ansible also collects facts, which are variables it discovers about each machine (the operating system, the memory, the IP addresses), so a play can adapt to what it finds.

This lesson covers where variables come from, how to read and create them, what facts are, and the part that surprises almost everyone: precedence, the rules that decide which value wins when the same name is defined in several places. If you have not written a playbook yet, read Playbooks and YAML Essentials first.

Ansible itself needs real servers and SSH, so it cannot run on this site. The commands and playbooks below are read-only. The runnable examples are small JavaScript stand-ins that copy the idea (layer merging, register, set_fact) so you can experiment. Each section says which is which.

Defining variables in a play

The simplest place is the vars keyword of a play. Values can be strings, numbers, booleans, lists and maps. You read a variable with Jinja2 double braces (the full story is in Jinja2 Templates and Filters).

YAML
- name: Configure the web tier
  hosts: web
  vars:
    http_port: 8080
    packages:
      - nginx
      - curl
    site:
      name: shop
      owner: deploy
  tasks:
    - name: Show what we will install
      ansible.builtin.debug:
        msg: "Site {{ site.name }} on port {{ http_port }} needs {{ packages | join(', ') }}"

Two rules save a lot of grief. First, a value that starts with {{ must be quoted, otherwise YAML tries to read it as a map. Second, variable names use letters, digits and underscores, and must not start with a digit; http-port is not a valid name.

The debug module prints a message (or a whole variable with var:) and changes nothing. It is the print statement of Ansible, and you will use it constantly.

Variables from files and the inventory

Putting everything in the play does not scale, so Ansible reads variables from several files.

  • vars_files lists extra YAML files to load into a play.
  • group_vars/<group>.yml holds values for every host in a group. group_vars/all.yml applies to every host.
  • host_vars/<host>.yml holds values for a single host.
  • -e (extra vars) passes values on the command line.
TEXT
inventories/
  production/
    hosts.ini
    group_vars/
      all.yml        # ntp_server, app_env
      web.yml        # http_port, max_clients
    host_vars/
      web2.yml       # max_clients for one special machine
Terminal
ansible-playbook site.yml -e "app_env=production"
ansible-playbook site.yml -e @overrides.yml    # load a whole file

The directory layout is detailed in Inventory: Hosts and Groups. Keeping data in group_vars and host_vars means a new server needs an inventory line, not a playbook edit.

Facts: what Ansible learns about a host

At the start of each play, Ansible runs the setup module on every host (this is the "Gathering Facts" step) and stores the results. Facts live under ansible_facts, and common ones are also available with an ansible_ prefix.

YAML
- hosts: all
  tasks:
    - name: Report the basics
      ansible.builtin.debug:
        msg: >-
          {{ inventory_hostname }} runs {{ ansible_facts['distribution'] }}
          {{ ansible_facts['distribution_version'] }} with
          {{ ansible_facts['processor_vcpus'] }} vCPUs

Useful facts include ansible_facts['os_family'] (for example Debian or RedHat), ansible_facts['hostname'], ansible_facts['default_ipv4']['address'] and ansible_facts['memtotal_mb']. To see every fact for a host, run an ad-hoc command:

Terminal
ansible web1 -m ansible.builtin.setup
ansible web1 -m ansible.builtin.setup -a "filter=ansible_distribution*"

Besides facts, Ansible provides magic variables that describe the run itself: inventory_hostname (the name in the inventory), groups (a map of group names to host lists), hostvars (every host's variables, so one host can read another's), group_names and play_hosts. Gathering facts takes a second or two per host, so large fleets sometimes disable it with gather_facts: false when the play does not need them (see Performance, Dynamic Inventory and AWX).

Creating variables while a play runs

Two features turn task results into variables.

register saves the result of a task. The result is a map: its keys depend on the module, but commonly include changed, rc, stdout, stdout_lines and stderr.

set_fact creates a variable from an expression, so you can compute something once and reuse it.

YAML
- hosts: web
  tasks:
    - name: Look for a listener on port 80
      ansible.builtin.command: ss -ltn 'sport = :80'
      register: port_check
      changed_when: false

    - name: Work out the worker count
      ansible.builtin.set_fact:
        workers: "{{ ansible_facts['processor_vcpus'] * 2 }}"

    - name: Print both
      ansible.builtin.debug:
        msg: "rc={{ port_check.rc }} workers={{ workers }}"

A registered variable and a set_fact value last for the rest of the playbook run on that host, but they disappear when the run ends (unless you cache facts, which is covered later). Registered results are also what conditionals and loops inspect.

Stand-in: a task runner with register and set_fact

This JavaScript model keeps a facts object and a per-host variables object. It is not Ansible's code; it only shows the data flow.

JS register and set_fact in a tiny task runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change ansible_processor_vcpus to 16 and run again to watch workers follow.

Precedence: which value wins?

The same variable can be defined in many places at once. Ansible has a fixed order, from weakest to strongest, and the strongest value wins. The full list has over twenty levels; this simplified version covers the ones you will meet daily:

flowchart LR
  A["role defaults<br/>(weakest)"] --> B["group_vars/all"]
  B --> C["group_vars/group"]
  C --> D["host_vars/host"]
  D --> E["play vars and vars_files"]
  E --> F["role vars, task vars"]
  F --> G["set_fact and register"]
  G --> H["extra vars -e<br/>(strongest)"]

Each arrow moves to a layer that overrides the one before it; extra vars on the command line beat everything.

Practical consequences:

  • Put sensible defaults in a role's defaults/main.yml so anyone can override them from inventory.
  • Put per-environment and per-host data in group_vars and host_vars.
  • Use -e for one-off overrides, and remember that nothing can beat it, not even set_fact.
  • Do not use role vars/ for things callers should change: it ranks high and is hard to override.
  • Inside the inventory, a more specific group beats a more general one, and a host beats its groups.

Stand-in: merging layers by precedence

This model resolves each variable by walking the layers from lowest to highest and recording where the final value came from.

JS Which layer wins?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real Ansible adds more layers and special merge options (maps can be merged instead of replaced with hash_behaviour, though the default, replace, is recommended), but the "later layer overwrites" idea is the same. When a value surprises you, run ansible-inventory --host web2 or add a debug task with var: max_clients to see the final value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A variable max_clients is set in group_vars/web.yml, in host_vars/web2.yml and in the play's vars. What wins for web2?

    Play vars rank above group_vars and host_vars. Inside the inventory a host beats its groups, but the play's own vars override both.
  2. 2. Which keyword stores the output of a task so later tasks can read .rc or .stdout?

    register saves the module's result map under the name you give. set_fact computes a new variable from an expression; debug only prints.
  3. 3. What are facts?

    Facts are gathered automatically at the start of a play (the setup module), for example the distribution, vCPU count and IP addresses.
  4. 4. You pass -e max_clients=10 on the command line. Which statement is true?

    Extra vars sit at the top of the precedence list, so nothing overrides them. That makes them useful for one-off changes and risky as a habit.

Summary

  • Variables come from vars, vars_files, group_vars, host_vars, roles, the command line (-e) and runtime features.
  • Facts are variables gathered per host by the setup module, available as ansible_facts[...]; magic variables such as inventory_hostname and hostvars describe the run.
  • register captures a task's result map; set_fact computes a new variable; debug prints one.
  • Precedence is a fixed order: role defaults are weakest, extra vars (-e) are strongest, and a host beats its groups.
  • Quote values that begin with {{, and keep defaults in roles, data in inventory files.

Next: Conditionals and Loops.