Aurora Store's playbooks already use inventory variables such as aurora_web_root, nginx_port or aurora_db_name, and every run starts with a mysterious Gathering Facts task. In this lesson you are going to master both worlds. On the one hand, variables: every way to define them (in the play, in files, in the inventory, on the command line), how to use lists and dictionaries, and which value wins when the same variable is defined in several places. On the other, facts: the information Ansible discovers about each server (operating system, memory, IPs…), how to filter it, how to create your own facts and how to query other hosts' data with magic variables. You will apply it to Aurora by configuring PostgreSQL on db1 from variables and by making web1 and web2 know where their database is, without writing it by hand.

Contents

  1. Where variables can be defined
  2. Variables in the playbook: vars, vars_files and task variables
  3. Extra variables on the command line (-e)
  4. Using variables: {{ }}, lists and dictionaries
  5. What facts are and how they're gathered
  6. Exploring facts with ansible_facts
  7. The setup module: filters and gather_subset
  8. Custom facts: facts.d and ansible_local
  9. Magic variables
  10. Creating variables at run time: set_fact
  11. Practice: PostgreSQL configured with variables
  12. Practice: the web servers discover the database with hostvars
  13. Variable precedence
  14. Fact caching

  1. Where variables can be defined

A variable is a name associated with a value that Ansible substitutes in playbooks through Jinja2 templating ({{ name }}). You already know the inventory ones. This is the full picture of the most common sources:

Source Where Scope Typical use in Aurora
Inventory inventory/group_vars/, inventory/host_vars/ Group or host Data for each environment and server (Lesson 2.2)
Play The play's vars: The play's hosts Derived values needed only by that playbook
Variable files The play's vars_files: The play's hosts Data shared across several playbooks
Task A task's vars: That task only One-off helper values
Command line -e / --extra-vars The whole run Tests and one-off values (highest priority)
Facts Gathered from the host Each host System information (OS, IPs, memory)
Registered register: Each host Task results (Lesson 3.7)
set_fact set_fact task Each host Values computed at run time
Roles A role's defaults/ and vars/ Role Module 4

Aurora's design rule: data goes in the inventory (because it changes per environment: lab, staging, production) and logic goes in the playbooks. Play variables are reserved for values that are derived or internal to the playbook itself.

  1. Variables in the playbook: vars, vars_files and task variables

vars in the play. A map of variables available to all the tasks in the play:

- name: Example of play variables
  hosts: webservers
  vars:
    aurora_maintenance: false
    aurora_support_phone: "+34 900 000 000"
  tasks:
    - name: Show the support phone number
      ansible.builtin.debug:
        msg: "Aurora support: {{ aurora_support_phone }}"

vars_files. Loads variables from one or more YAML files, with paths relative to the playbook:

- name: Example of vars_files
  hosts: webservers
  vars_files:
    - vars/aurora_contact.yml
# vars/aurora_contact.yml
---
aurora_support_phone: "+34 900 000 000"
aurora_support_hours: "Mon-Fri 9:00-18:00"

It's useful for sharing the same set of data across several playbooks or for keeping sensitive data separate (in Lesson 5.4 you'll see that vars_files is a common way to load files encrypted with Vault). In Aurora we don't need it for now: the inventory plays that role.

vars in a task. They exist only during that task:

    - name: Create the backup directory
      ansible.builtin.file:
        path: "{{ backup_dir }}"
        state: directory
        mode: "0750"
      vars:
        backup_dir: /var/backups/aurora

  1. Extra variables on the command line (-e)

Extra variables are passed at run time and always win over any other definition. Three formats:

# key=value (values are always text)
ansible-playbook webservers.yml --check --diff -e "nginx_port=8080"

# JSON (respects types: numbers, booleans, lists)
ansible-playbook webservers.yml --check -e '{"nginx_port": 8080, "aurora_maintenance": true}'

# From a YAML or JSON file (@ prefix)
ansible-playbook webservers.yml --check -e @tests.yml

Use them for tests, for values that change on every run (a version to deploy, for example) or from CI/CD tools (Module 8). Not to configure Aurora permanently: anything that only exists on the command line isn't recorded in the repository. And remember that with key=value everything is text: -e "aurora_maintenance=false" produces the string "false", which evaluates as true in a condition. For booleans, use JSON.

  1. Using variables: {{ }}, lists and dictionaries

Variables are used with the Jinja2 syntax {{ name }}, in any value of a playbook or of the inventory (remember the quotes if the value starts with {{, Lesson 3.2).

Variables can hold lists and dictionaries. Suppose these definitions:

aurora_payment_methods:
  - card
  - transfer
  - bizum

aurora_company:
  name: Aurora Store
  address:
    city: Valencia
    zip: "46001"
  vat-id: ESX0000000X
Expression Result Notes
{{ aurora_payment_methods }} ['card', 'transfer', 'bizum'] The whole list
{{ aurora_payment_methods[0] }} card Indexes start at 0
{{ aurora_payment_methods[-1] }} bizum Negative indexes count from the end
{{ aurora_company.name }} Aurora Store Dot notation
{{ aurora_company['name'] }} Aurora Store Bracket notation
{{ aurora_company.address.city }} Valencia Nested
{{ aurora_company['vat-id'] }} ESX0000000X Brackets only (the key contains a hyphen)

Dot or brackets? Both work in most cases, but brackets are safer:

  • If the key contains special characters (vat-id) or starts with a number.
  • If the key is stored in another variable: hostvars[aurora_db_server] (with a dot it would look for a key literally called aurora_db_server).
  • If the key matches a Python method (keys, items, values, update…): my_dict.items returns the method, not your data.

In Aurora we'll use brackets for ansible_facts and hostvars, and dots for our own simple structures. Data transformations (filters such as join, default, map…) are covered in depth in Lesson 5.3; here you'll only use a few very basic ones, explained as they come up.

  1. What facts are and how they're gathered

Facts are variables that Ansible discovers on each host: operating system, version, architecture, memory, CPUs, disks, network interfaces, IPs, hostname, Python version… They're gathered by the setup module, which runs automatically at the start of every play: it's the TASK [Gathering Facts] task.

sequenceDiagram
    participant C as Control node
    participant H as db1
    C->>H: setup module (Gathering Facts)
    H->>H: Inspects the system
    H-->>C: JSON with hundreds of facts
    C->>C: Stores them in db1's ansible_facts
    C->>H: Play tasks (can use the facts)

It's controlled with the gather_facts play keyword (Lesson 3.4): true by default, false to skip gathering them. Facts can be used in any later task on the same host and, as you'll see, from other hosts too through hostvars.

  1. Exploring facts with ansible_facts

All of a host's facts are in the ansible_facts dictionary. Create an exploration playbook (you won't keep it in the repository), facts-demo.yml:

---
- name: Explore the facts of the Aurora servers
  hosts: aurora
  tasks:
    - name: Show a system summary
      ansible.builtin.debug:
        msg:
          - "System: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }} ({{ ansible_facts['distribution_release'] }})"
          - "Family: {{ ansible_facts['os_family'] }}"
          - "CPUs: {{ ansible_facts['processor_vcpus'] }} - Memory: {{ ansible_facts['memtotal_mb'] }} MB"
          - "IPs: {{ ansible_facts['all_ipv4_addresses'] }}"
          - "Default route IP: {{ ansible_facts['default_ipv4']['address'] }}"
ansible-playbook facts-demo.yml --limit db1
TASK [Show a system summary] ***************************************************
ok: [db1] =>
    msg:
    - 'System: Ubuntu 24.04 (noble)'
    - 'Family: Debian'
    - 'CPUs: 2 - Memory: 1967 MB'
    - 'IPs: [''10.0.2.15'', ''192.168.56.21'']'
    - 'Default route IP: 10.0.2.15'

Most commonly used facts:

Fact (ansible_facts['...']) Example on db1 Typical use
distribution, distribution_version Ubuntu, 24.04 Distribution-specific tasks
os_family Debian Choose apt or dnf (Lesson 3.6)
distribution_release noble Package repositories
architecture x86_64 Binary downloads
memtotal_mb 1967 Tune service memory
processor_vcpus 2 Tune processes or workers
hostname, fqdn db1, db1 Host names
all_ipv4_addresses list of IPs Inventory addresses
default_ipv4 dictionary (address, interface, gateway…) "Main" IP (careful!)
mounts list of filesystems Disk space
python.version version dictionary Diagnostics

Notice an important detail of the lab: the default route IP is 10.0.2.15, the NAT interface Vagrant uses to give the machines Internet access, and it's the same on all three. The IP they use to talk to each other (192.168.56.21) is on another interface. You'll take this into account in section 12.

ansible_distribution versus ansible_facts['distribution']. In older documentation you'll see facts as standalone variables with the ansible_ prefix (ansible_distribution, ansible_memtotal_mb). They work for backward compatibility, but they clutter the variable namespace and Ansible is moving towards no longer injecting them. Always use ansible_facts['...'], without the prefix.

  1. The setup module: filters and gather_subset

To explore facts quickly, nothing beats the setup module in an ad hoc command, with the filter parameter (it accepts wildcards):

ansible db1 -m ansible.builtin.setup -a 'filter=ansible_memtotal_mb'
ansible db1 -m ansible.builtin.setup -a 'filter=ansible_distribution*'
ansible aurora -m ansible.builtin.setup -a 'filter=ansible_processor_vcpus'
db1 | SUCCESS => {
    "ansible_facts": {
        "ansible_distribution": "Ubuntu",
        "ansible_distribution_file_parsed": true,
        "ansible_distribution_file_path": "/etc/os-release",
        "ansible_distribution_file_variety": "Debian",
        "ansible_distribution_major_version": "24",
        "ansible_distribution_release": "noble",
        "ansible_distribution_version": "24.04"
    },
    "changed": false
}

In the module's output the names carry the ansible_ prefix; inside a playbook's ansible_facts dictionary they're used without it (ansible_facts['distribution']).

Gathering all the facts takes time (on servers with many disks or interfaces, quite a lot). With the gather_subset play keyword you choose which subsets to gather:

Subset What it includes
all Everything (default)
min The minimum: distribution, hostname, user, Python, date… (always gathered)
hardware CPU, memory, disks, mount points
network Interfaces, IPs, routes
virtual Virtualization type
- name: Play that only needs network data
  hosts: webservers
  gather_subset:
    - "!all"
    - network

!all excludes everything except min, and then network is added. It's an optimization: you'll come back to it in Lessons 5.8 and 9.3.

  1. Custom facts: facts.d and ansible_local

In addition to what Ansible discovers, you can publish your own facts on each server. If the /etc/ansible/facts.d/ directory exists on the host, setup reads the *.fact files it contains (in INI or JSON format; or, if they're executable, their JSON output) and adds them under ansible_local.

This is useful so that each server "knows" things that can't be discovered: which environment it belongs to, what role it plays, which version of the application it has deployed. Add these three tasks at the end of common.yml:

    - name: Create the local facts directory
      ansible.builtin.file:
        path: /etc/ansible/facts.d
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Publish the Aurora Store local facts
      ansible.builtin.copy:
        dest: /etc/ansible/facts.d/aurora.fact
        owner: root
        group: root
        mode: "0644"
        content: |
          [general]
          env={{ aurora_env }}
          domain={{ aurora_domain }}
          groups={{ group_names | join(',') }}
          managed_by=aurora-infra
      register: aurora_local_facts

    - name: Re-read the local facts if they have changed
      ansible.builtin.setup:
        filter: ansible_local
      when: aurora_local_facts.changed
  • The aurora.fact file is in INI format: a [general] section with key=value pairs. It must have 0644 permissions, not executable (if it were, Ansible would try to run it).
  • group_names is a magic variable (section 9) with the list of the host's groups; the join(',') filter turns it into comma-separated text.
  • The third task runs setup again (only for ansible_local) if the file has just changed: facts were gathered at the start of the play, when the file didn't exist yet. It's the same temporary register + when pattern from Lesson 3.3.

Run it and query:

ansible-playbook common.yml
ansible web1 -m ansible.builtin.setup -a 'filter=ansible_local'
web1 | SUCCESS => {
    "ansible_facts": {
        "ansible_local": {
            "aurora": {
                "general": {
                    "domain": "aurora-store.example",
                    "env": "lab",
                    "groups": "aurora,webservers",
                    "managed_by": "aurora-infra"
                }
            }
        }
    },
    "changed": false
}

In any later playbook they'll be available as ansible_local['aurora']['general']['env'] (the file name without .fact, the section and the key). And any tool on the server can read the file directly.

  1. Magic variables

Magic variables are defined automatically by Ansible; you can't overwrite them. They're the key for a host to know its context and the data of the others:

Variable Contents Example (running on web1)
inventory_hostname The host's name in the inventory web1
inventory_hostname_short Up to the first dot web1
group_names Groups the host belongs to (without all) ['aurora', 'webservers']
groups All the inventory groups with their hosts groups['dbservers'] → ['db1']
hostvars The variables of all hosts hostvars['db1']['postgresql_port'] → 5432
ansible_play_hosts Hosts in the current play that are still active (excluding failed ones) ['web1', 'web2']
ansible_play_batch Hosts in the current batch (relevant with serial, Lesson 5.7) ['web1', 'web2']
playbook_dir The playbook's directory /home/student/aurora-infra
inventory_dir The inventory's directory /home/student/aurora-infra/inventory
ansible_check_mode true if running with --check false

play_hosts is the old name for ansible_play_hosts; it's deprecated and shouldn't be used.

hostvars deserves attention: for each host in the inventory, it holds its inventory variables (group_vars, host_vars, ansible_host…) and, if they've already been gathered in this run, its facts. That way, a web server can read db1's variables even if db1 isn't in its play.

  1. Creating variables at run time: set_fact

The ansible.builtin.set_fact module creates (or redefines) variables for the current host from a computation, and they remain available for the rest of the run (including the following plays):

    - name: Compute the recommended cache size
      ansible.builtin.set_fact:
        aurora_cache_mb: "{{ (ansible_facts['memtotal_mb'] * 0.25) | int }}"

    - name: Show the computed value
      ansible.builtin.debug:
        msg: "Recommended cache on {{ inventory_hostname }}: {{ aurora_cache_mb }} MB"

Use it for derived values you're going to use several times and that depend on facts or other run-time data. Don't use it for fixed values: those go in the inventory. set_fact variables have very high precedence (section 13).

  1. Practice: PostgreSQL configured with variables

You're going to configure PostgreSQL's main parameters on db1 from inventory variables. On Ubuntu, the main postgresql.conf file includes every file in the conf.d/ directory, so instead of editing the package's file you'll create your own: /etc/postgresql/16/main/conf.d/aurora.conf.

First, complete inventory/group_vars/dbservers.yml:

---
# Variables for the Aurora Store database servers
postgresql_version: 16
postgresql_port: 5432
postgresql_max_connections: 100
postgresql_shared_buffers: 128MB        # group default; db1 raises it in host_vars
postgresql_listen_addresses: "localhost,{{ ansible_host }}"
aurora_db_name: aurora
aurora_db_user: aurora
  • postgresql_shared_buffers: 128MB is a default value for any server in the group. db1 already had postgresql_shared_buffers: 512MB in inventory/host_vars/db1.yml (Lesson 2.2), which wins because it's more specific. That way, a future db2 without host_vars would work with the group's value.
  • postgresql_listen_addresses uses another variable: ansible_host. Variables are evaluated lazily, at the moment they're used and for each host, so on db1 it will be localhost,192.168.56.21.

Now add two tasks to dbservers.yml, between Install PostgreSQL... and Ensure PostgreSQL is started...:

    - name: Configure the PostgreSQL parameters for Aurora Store
      ansible.builtin.copy:
        dest: "/etc/postgresql/{{ postgresql_version }}/main/conf.d/aurora.conf"
        owner: postgres
        group: postgres
        mode: "0644"
        content: |
          # Managed by Ansible (aurora-infra). Do not edit by hand.
          listen_addresses = '{{ postgresql_listen_addresses }}'
          port = {{ postgresql_port }}
          max_connections = {{ postgresql_max_connections }}
          shared_buffers = {{ postgresql_shared_buffers }}
      register: postgresql_config

    - name: Restart PostgreSQL if its configuration has changed (temporary)
      ansible.builtin.systemd_service:
        name: postgresql
        state: restarted
      when: postgresql_config.changed
  • The path uses postgresql_version: if Aurora ever migrates to PostgreSQL 17, changing the variable will be enough.
  • These four parameters only take effect when PostgreSQL is restarted. It's restarted only if the file has changed: the same temporary pattern from Lesson 3.3, which handlers will replace in Lesson 5.1.

Run it, verify and check idempotency:

ansible-playbook dbservers.yml --diff
ansible db1 -a 'psql -tAc "SHOW shared_buffers"' -b --become-user postgres
ansible db1 -a 'ss -ltn' -b
ansible-playbook dbservers.yml

The query returns 512MB (the host_vars value, not the group's) and ss shows PostgreSQL listening on 127.0.0.1:5432 and 192.168.56.21:5432. The second run ends with changed=0.

  1. Practice: the web servers discover the database with hostvars

The store application, which will be deployed on web1 and web2, will need to know where the database is. Instead of writing 192.168.56.21 in the web server playbook (and having to change it if the database moves), you'll compute it from the inventory.

Add a vars: section to the play in webservers.yml, right after become: true:

  vars:
    aurora_db_server: "{{ groups['dbservers'][0] }}"
    aurora_db_host: "{{ hostvars[aurora_db_server]['ansible_host'] }}"
    aurora_db_port: "{{ hostvars[aurora_db_server]['postgresql_port'] }}"
  • groups['dbservers'][0] is the first (and only) host in the dbservers group: db1.
  • hostvars[aurora_db_server]['ansible_host'] reads db1's ansible_host variable: 192.168.56.21. Notice the brackets: the key is stored in a variable.
  • hostvars[aurora_db_server]['postgresql_port'] reads a variable from group_vars/dbservers.yml that the web servers don't have: it's only accessible through hostvars.

And add these tasks at the end of tasks:, after the firewall ones:

    - name: Compute the database connection string
      ansible.builtin.set_fact:
        aurora_db_dsn: "postgresql://{{ hostvars[aurora_db_server]['aurora_db_user'] }}@{{ aurora_db_host }}:{{ aurora_db_port }}/{{ hostvars[aurora_db_server]['aurora_db_name'] }}"

    - name: Create the Aurora configuration directory
      ansible.builtin.file:
        path: /etc/aurora
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Publish the database connection details
      ansible.builtin.copy:
        dest: /etc/aurora/db.conf
        owner: root
        group: root
        mode: "0644"
        content: |
          # Managed by Ansible (aurora-infra). Do not edit by hand.
          AURORA_DB_HOST={{ aurora_db_host }}
          AURORA_DB_PORT={{ aurora_db_port }}
          AURORA_DB_NAME={{ hostvars[aurora_db_server]['aurora_db_name'] }}
          AURORA_DB_USER={{ hostvars[aurora_db_server]['aurora_db_user'] }}
          AURORA_DB_DSN={{ aurora_db_dsn }}
ansible-playbook webservers.yml --diff
ansible webservers -a 'cat /etc/aurora/db.conf'
web1 | CHANGED | rc=0 >>
# Managed by Ansible (aurora-infra). Do not edit by hand.
AURORA_DB_HOST=192.168.56.21
AURORA_DB_PORT=5432
AURORA_DB_NAME=aurora
AURORA_DB_USER=aurora
AURORA_DB_DSN=postgresql://[email protected]:5432/aurora

(The password will be added once it exists, encrypted with Vault, in Lesson 5.4.)

What if we used db1's facts? You might think of hostvars['db1']['ansible_facts']['default_ipv4']['address']. There are two problems:

  1. db1's facts are only in hostvars if they've been gathered in this run. With ansible-playbook site.yml they are (the dbservers play runs first), but with ansible-playbook webservers.yml they aren't: the variable would be undefined and the task would fail. Inventory variables, on the other hand, are always available.
  2. As you saw in section 6, in the lab default_ipv4 is Vagrant's NAT IP (10.0.2.15), not the one on the private network.

That's why Aurora uses ansible_host. The lesson: other hosts' facts are useful, but they depend on the execution order; fact caching (section 14) softens that problem.

Commit the work:

git add common.yml dbservers.yml webservers.yml inventory/group_vars/dbservers.yml
git commit -m "Variables and facts: local facts, PostgreSQL configuration and connection details"
rm -f facts-demo.yml

  1. Variable precedence

When a variable is defined in several places, Ansible applies a documented precedence order (22 levels). This table summarizes the main sources, from lowest to highest priority (the bottom one wins):

Priority Source Example in Aurora
1 (lowest) Command-line values that aren't variables (-u, -b) -u vagrant
2 A role's defaults/ Module 4
3 Inventory group_vars/all aurora_timezone
4 Playbook-adjacent group_vars/all (not used)
5 Inventory group_vars/<group> postgresql_shared_buffers: 128MB
6 Playbook-adjacent group_vars/<group> (not used)
7 Inventory host_vars/<host> postgresql_shared_buffers: 512MB on db1
8 Playbook-adjacent host_vars/<host> (not used)
9 Host facts ansible_facts, ansible_local
10 The play's vars: aurora_db_host
11 The play's vars_files: —
12 A role's vars/ Module 4
13 A block's or a task's vars: —
14 include_vars Lesson 4.5
15 set_fact and registered variables aurora_db_dsn
16 Role and include parameters Module 4
17 (highest) Extra variables (-e) -e nginx_port=8080

Key ideas to keep your bearings:

  • The more specific wins over the general: all < group < host.
  • The playbook wins over the inventory: the play's vars: overrides group_vars and host_vars. That's why in Aurora we don't redefine in the play variables that are already in the inventory.
  • set_fact and register win over almost everything, and -e always wins.
  • Inventory connection variables (ansible_user…) win over the equivalent command-line options (-u), as you saw in Lesson 2.2.
  • "Playbook-adjacent group_vars/" means group_vars/ and host_vars/ directories placed next to the playbook file. Aurora only uses the inventory ones, to have a single source of data.

To check which value a variable really has on a host, there's nothing like asking:

ansible db1 -m ansible.builtin.debug -a 'var=postgresql_shared_buffers'
db1 | SUCCESS => {
    "postgresql_shared_buffers": "512MB"
}

  1. Fact caching

By default, facts only live for the duration of a run: the next ansible-playbook gathers them again. Ansible can store them in a cache (JSON files, Redis…) to reuse them across runs, which speeds up playbooks and lets you query the facts of hosts that aren't taking part in the current run. It's configured in ansible.cfg (fact_caching, fact_caching_connection, fact_caching_timeout) together with gathering = smart. You'll configure it in Lesson 9.3, which is devoted to performance.

Common Mistakes and Tips

  • 'dict object' has no attribute 'postgresql_port' when using hostvars: the host or variable name is misspelled, or the variable doesn't exist for that host. Check it with ansible-inventory --host db1.
  • 'ansible_facts' is undefined or undefined fact keys: the play has gather_facts: false, or you're reading facts from another host that haven't been gathered in this run.
  • Booleans passed with -e key=value: they arrive as text ("false"). Use -e '{"aurora_maintenance": false}'.
  • Redefining an inventory variable in the play's vars:: the play wins and the inventory's per-host values stop applying without you noticing. Keep the names different (that's why it's aurora_db_host and not postgresql_listen_addresses on the web servers).
  • Defining a variable in terms of itself (aurora_db_name: "{{ hostvars['db1']['aurora_db_name'] }}" in the play): it can cause a recursion error. Use another name or the expression directly.
  • A .fact file with execute permissions: Ansible runs it instead of reading it, and fails. Use mode: "0644".
  • Tip: when you're unsure where a value comes from, use ansible <host> -m ansible.builtin.debug -a 'var=<variable>' and ansible-inventory --host <host>.

Exercises

Exercise 1: A server report

Write a test playbook that, for each server in aurora, uses debug to show a line such as web1: Ubuntu 24.04, 2 CPU, 961 MB, groups: aurora, webservers, environment: lab, using facts, the group_names magic variable and Aurora's local fact.

Exercise 2: Precedence in action

Without modifying any file, find out the value of postgresql_shared_buffers on db1 and explain where it comes from. Then simulate with --check --diff what would happen when running dbservers.yml with -e postgresql_shared_buffers=256MB. Which tasks would change?

Exercise 3: All the web server IPs

Add (temporarily) a debug task to the play in dbservers.yml that shows the list of IPs (ansible_host) of all the web servers, going through groups['webservers']. Hint: you can build the list with a Jinja2 expression: {{ groups['webservers'] | map('extract', hostvars, 'ansible_host') | list }}.

Solutions

Exercise 1.

---
- name: Aurora server report
  hosts: aurora
  tasks:
    - name: Show the report
      ansible.builtin.debug:
        msg: >-
          {{ inventory_hostname }}:
          {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }},
          {{ ansible_facts['processor_vcpus'] }} CPU,
          {{ ansible_facts['memtotal_mb'] }} MB,
          groups: {{ group_names | join(', ') }},
          environment: {{ ansible_local['aurora']['general']['env'] }}

The >- folded block (Lesson 3.2) joins the lines into one. ansible_local exists because common.yml published the aurora.fact file and setup reads it every time facts are gathered.

Exercise 2.

ansible db1 -m ansible.builtin.debug -a 'var=postgresql_shared_buffers'
ansible-playbook dbservers.yml --check --diff -e postgresql_shared_buffers=256MB

It's 512MB, from inventory/host_vars/db1.yml, which wins over 128MB from group_vars/dbservers.yml because host variables are more specific than group variables. With -e (highest precedence), the simulation shows shared_buffers = 256MB in aurora.conf in the diff and also predicts the PostgreSQL restart. Since it's --check, nothing changes.

Exercise 3.

    - name: Show the web server IPs
      ansible.builtin.debug:
        msg: "{{ groups['webservers'] | map('extract', hostvars, 'ansible_host') | list }}"

It shows ['192.168.56.11', '192.168.56.12']. map('extract', hostvars, 'ansible_host') takes each host name and extracts its ansible_host from hostvars. Filters are covered in depth in Lesson 5.3; in the next lesson you'll achieve something similar in a more readable way with a loop. Remove the task when you're done.

Conclusion

You now know how to define variables at every level (inventory, vars, vars_files, tasks, -e), use lists and dictionaries with dot and bracket notation, and understand which value wins thanks to the precedence table. You know facts: how they're gathered, how to query them in ansible_facts, filter them with setup and gather_subset, and how to publish your own facts in /etc/ansible/facts.d/ (Aurora now has its aurora.fact on every server). You've used magic variables (inventory_hostname, groups, group_names, hostvars, ansible_play_hosts) and set_fact. And you've applied it to Aurora: PostgreSQL on db1 is configured with group and host variables, and web1 and web2 get db1's connection details through hostvars, without writing a single IP by hand. So far, every task always runs, and only once. In the next lesson, Conditionals and Loops, you'll learn to run tasks only when a condition is met and to repeat them for each item in a list: you'll create the Aurora team's users, install packages according to the distribution and manage several databases at once.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved