Ansible Lesson 2: From “It Works” to “Production-Ready”

Refactor the single-file myapp playbook from Lesson 1 into roles and collection dependencies, then add Vault secrets, error handling, lint, Molecule tests, and finally package everything into an execution environment (EE)
ansible-core 2.21Ansible community package 14.xansible-lint 26.11 · Molecule 26.11ansible-builder 3.2 · navigator 26.11Verified against official docs · 2026-11
Overall learning objectives
  • Use ansible-galaxy role init to split the playbook into role, clearly explain the difference between defaults/ and vars/ , as well as meta/main.yml dependencies and meta/argument_specs.yml argument validation, and choose between import_role (static) and include_role (dynamic) based on the scenario.
  • Use FQCN to reference modules, use requirements.yml to pin collection versions and install them into the project’s collections/, and understand the order in which Ansible looks up collections.
  • Remember the 22 levels of variable precedence (the most commonly used ones: role defaults → inventory group_vars → host_vars → play vars → role vars → set_fact → extra vars), and design non-conflicting group_vars/,host_vars/ directory and role-prefix naming conventions.
  • Use Ansible Vault encrypt an entire file or a single value (encrypt_string), use --vault-id to separate dev/prod passwords, together with no_log to keep secrets out of logs, and explain the trade-offs between Vault and external secret management (Azure Key Vault, etc.).
  • Use block/rescue/always,failed_when,changed_when,any_errors_fatal to write tasks where failures can be rolled back and results are trustworthy; use tags,--check --diff to run safe partial executions and dry runs.
  • Use ansible-lint (production profile) and Molecule (Docker containers + idempotence testing) to set up quality gates for roles; use ansible-builder to build the execution environment, use ansible-navigator to run the same playbook inside the EE.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (node1–node3)
0Before classTransition and warm-upCheck the Lesson 1 control node, the 3 managed nodes, and myapp; rebuild in one step if anything is missing8-item self-assessment of “production readiness”ansible all -m ping All green
100–08Role structure and reuserole directory conventions, defaults vs vars, handlers, meta dependencies and argument_specs, roles: / import_role / include_role, static vs dynamicStatic import vs dynamic include: parse-time vs runtime comparisonSplit myapp into three roles: common / redis / myapp
208–14Collections and ansible-galaxyFQCN, collection search path, requirements.yml, version ranges and pinning, offline tarballs, verifyFQCN resolution and collection installation flowInstall community.general / ansible.posix within the project
314–21Variable precedence and organization22 precedence levels, the 8 most common, group_vars/host_vars directories, extra vars, naming conventions, stricter templating and conditionals from 2.19 onwardCore animation: same-named variable overridden layer by layer to reach the final valueSame variable defined at 5 levels, verified with debug
421–28Ansible Vault and secretsencrypt / encrypt_string / rekey, vault-id labels, password files and client scripts, no_log, vault_ indirect variables, external secret managementVault decryption flow (vault-id match → PBKDF2 → HMAC → AES)Encrypt the Redis password, with separate dev/prod passwords
528–35Error handlingblock / rescue / always, ignore_errors, failed_when, changed_when, any_errors_fatal, max_fail_percentageMulti-host failure handling simulatorAutomatic rollback to the previous version when a release fails
635–41Tags, check, and diff--tags / --skip-tags, always / never, tag inheritance for import vs include, check_mode compatibility, --diffTag filter: which tasks will runPush configuration only, dry-run changes
741–51ansible-lint and Moleculelint rules and profiles, .ansible-lint, Molecule scenarios, Docker containers, converge → idempotence → verifyMolecule test sequence (including an idempotence failure)Add lint + Molecule to the myapp role
851–60Execution environments and ansible-navigatorWhy EEs are needed, execution-environment.yml v3, ansible-builder build stages, navigator run / settings / artifactEE build and run flow + troubleshooting treeBuild myapp-ee and deploy with navigator
—After classCheat sheet · Capstone labmyapp roleization + Vault + lint + Molecule + EE, end to endFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Refactor the playbook into reusable roles✓·✓···✓·ansible-galaxy role initThree myapp roles
Choosing static vs dynamic reuse✓····✓··import_role / include_roleM1, M6 labs
Manage collection dependencies and versions·✓····✓✓ansible-galaxy collection install -rrequirements.yml
Predict final variable values and avoid conflicts✓·✓✓····ansible-inventory --host,debug5-level override lab
Encrypt and use secrets··✓✓···✓ansible-vault encrypt_string --vault-idRedis password
Failure handling and rollback····✓·✓·block/rescue/alwaysFailure rollback
Safe partial execution and dry runs·····✓··--tags,--check --diffPush config only
Static checks and automated testing····✓·✓·ansible-lint,molecule testMolecule scenarios
Portable runtime environment·✓·····✓ansible-builder build,ansible-navigator runmyapp-ee

Out-of-scope topics (and where to learn them)

TopicWhy not covered hereWhere to learn
Azure Key Vault lookups, managed identitiesRequires cloud resources; this lesson only covers the trade-offs between Vault and external secretsLesson 3 Module 5
AWS Secrets Manager / SSM Parameter Store lookupBelongs to the AWS topicLesson 4
Running lint/Molecule in CI, using EEs in AWX/AAP, Event-Driven AnsibleBelongs to automated ops pipelinesLesson 5
Writing custom modules and plugins, publishing your own collection to Galaxy / Automation HubAimed at content developers; exceeds 1 hourLesson 7;Developing collections
Performance tuning (forks, pipelining, strategy, mitogen)Belongs to deep troubleshooting and optimizationLesson 7

How to use this courseware

10 pages per module
Theory · Diagrams · Animations · Commands · Labs · Production cases · Troubleshooting · Quizzes · Audio · Video. We recommend reading “Theory” and “Animation” first, then doing the “Lab”. All labs take place in the same project directory ~/ansible-lab and build up step by step.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress, which is saved in this browser (if local storage is blocked, progress is cleared on refresh).
Chinese audio
The “Audio” page uses the browser’s built-in Web Speech API (en-US) to read the script aloud; without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes This lesson is based on ansible-core 2.21 (GA 2026-05; the control node requires Python 3.12–3.14) and Ansible community package 14.x as the baseline; ansible-core 2.19 reaches EOL in 2026-11. Tool versions verified on PyPI on 2026-11-15: ansible-lint 26.11.0, molecule 26.11.0, molecule-plugins 26.11.0, ansible-navigator 26.11.0 (all released 2026-11), ansible-builder 3.2.0 (2026-10-13). Collection versions verified on Galaxy: community.general 14.0.1, ansible.posix 2.2.2, community.docker 5.4.0. Special note: Starting with ansible-core 2.19, the templating engine introduces data tagging: conditional expressions must return a boolean, and nested expressions are no longer allowed {{ }}, and “untrusted” strings are no longer rendered as templates; Modules 3 and 5 cover this in detail.

Module 0 · Transition and warm-up (complete before class)

Confirm that the Lesson 1 control node, node1–node3, and myapp are still working, install the tools this lesson needs, then score myapp’s “production readiness”
Before class ≈ 10 minansible-core 2.21 · Python 3.12+
Prerequisites
  • CompletedLesson 1: the control node (Ubuntu 24.04, an Azure VM or a local machine) has Ansible installed via pipx; a Docker network anslab (172.30.0.0/24) contains 3 Ubuntu 24.04 containers running sshd and systemd: node1 (172.30.0.11),node2 (172.30.0.12),node3 (172.30.0.13). The control node SSHes directly to the container IPs on port 22; the project directory ~/ansible-lab contains ansible.cfg,inventory/hosts.ini, group_vars/host_vars, and the Lesson 1 Module 8 site.yml.
  • Lesson 1 topology: [lb] and [cache] are both node1 (nginx load balancer + Redis),[app] are node2 and node3 (myapp: Flask + gunicorn, port 5000, managed by systemd),[lab:children] contain three groups. The app reaches Redis via node1’s address 172.30.0.11, and users reach the app through http://172.30.0.11/ nginx.
  • The control node already has Docker Engine 29 installed (from the Docker course); both Molecule and ansible-builder in this lesson use it.
Conventions This lesson reuses all of Lesson 1’s settings (network, IPs, group names,remote_user = ansible,private_key_file = ~/.ssh/ansible_lab). This lesson renames Lesson 1’s app_port,gunicorn_workers,redis_host,app_dir to role-prefixed names myapp_port,myapp_workers,myapp_redis_host,myapp_home (Module 3 covers naming conventions); Redis-related tasks are wrapped into a redis role, but still applied to the cache group.

Step 1: Check the control node and managed nodes

cd ~/ansible-lab
ansible --version | head -3
python3 --version
docker ps --format '{{.Names}}\t{{.Status}}\t{{.Networks}}' | grep node
ansible-inventory --graph
ansible all -m ansible.builtin.ping -o
ansible [core 2.21.5]
  config file = /home/azureuser/ansible-lab/ansible.cfg
  configured module search path = ['/home/azureuser/.ansible/plugins/modules', ...]
Python 3.12.3
node3   Up 2 days   anslab
node2   Up 2 days   anslab
node1   Up 2 days   anslab
@all:
  |--@ungrouped:
  |--@lab:
  |  |--@lb:
  |  |  |--node1
  |  |--@cache:
  |  |  |--node1
  |  |--@app:
  |  |  |--node2
  |  |  |--node3
node1 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"}
node2 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"}
node3 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"}

Note: docker ps --format in the {{.Names}} is a Go template, unrelated to Jinja2. ansible --version The first line must be core 2.21.x (or 2.20.x); if it shows 2.18 or earlier, please pipx upgrade --include-injected ansible.

Step 2 (only if the environment was deleted): minimally rebuild the end state of Lesson 1

The following commands are equivalent to the results of Lesson 1 Modules 0 and 8. The node image ans-node:24.04 uses the ~/ansible-lab/nodes/Dockerfile build (Ubuntu 24.04 + systemd as PID 1 + sshd + sudo + python3; user ansible logs in using ~/.ssh/ansible_lab public-key login). Running systemd inside a container requires privileges and sharing the host cgroup, so use VMs in production. You can also switch to 3 small VMs or multipass. Docker Desktop (macOS/Windows) cannot reach 172.30.0.x directly from the host; follow the instructions in Lesson 1 Module 0 for this.

cd ~/ansible-lab/nodes && docker build -t ans-node:24.04 . && cd ..
docker network create --subnet 172.30.0.0/24 anslab
for i in 1 2 3; do
  docker run -d --name node$i --hostname node$i \
    --network anslab --ip 172.30.0.1$i \
    --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
    --tmpfs /run --tmpfs /run/lock \
    ans-node:24.04
done
for ip in 172.30.0.11 172.30.0.12 172.30.0.13; do ssh-keygen -R $ip >/dev/null 2>&1; done
ssh-keyscan -t ed25519 172.30.0.11 172.30.0.12 172.30.0.13 >> ~/.ssh/known_hosts 2>/dev/null
[defaults]
inventory = inventory/hosts.ini
remote_user = ansible
private_key_file = ~/.ssh/ansible_lab
interpreter_python = auto_silent
forks = 10
retry_files_enabled = False

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
pipelining = False
[lb]
node1 ansible_host=172.30.0.11

[cache]
node1

[app]
node2 ansible_host=172.30.0.12
node3 ansible_host=172.30.0.13

[lab:children]
lb
cache
app
# Lesson 1 variable file (excerpt; the parts used in this lesson)
mkdir -p inventory/group_vars inventory/host_vars
printf 'ntp_server: pool.ntp.org\napp_port: 5000\nmotd_role: generic\n' > inventory/group_vars/all.yml
cat > inventory/group_vars/app.yml <<'VARS'
motd_role: app
gunicorn_workers: 2
app_dir: /opt/myapp
redis_host: "{{ hostvars[groups['cache'][0]]['ansible_host'] }}"
VARS
printf 'gunicorn_workers: 4\n' > inventory/host_vars/node3.yml

The Lesson 1 Module 8 site.yml (5 plays: gather facts → Redis (cache) → myapp (app) → nginx load balancer (lb) → end-to-end verification),files/myapp/app.py,files/myapp/requirements.txt,templates/myapp.service.j2,templates/nginx-myapp.conf.j2 copy it verbatim from Lesson 1’s “Lab 8”. It already uses FQCNs and runs reliably, but it still falls short of “production-ready”: all logic is piled into one file and cannot be reused or tested separately; variables lack role prefixes and argument validation; Redis protected-mode no and has no password set; there is no rollback when a release fails; you cannot update only the configuration; there is no lint or automated testing; and switching to a different control node may behave differently due to collection/Python version differences. This lesson addresses each of these.

ansible-playbook site.yml
curl -s http://172.30.0.11/ ; curl -s http://172.30.0.11/
curl -s http://172.30.0.12:5000/healthz
PLAY RECAP *********************************************************************
localhost  : ok=3   changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
node1      : ok=12  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
node2      : ok=11  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
node3      : ok=11  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
Hello from node2, hits=12
Hello from node3, hits=13
ok

Step 3: Install the tools this lesson needs

ansible-lint, Molecule, ansible-navigator, and ansible-builder are all standalone Python packages. We recommend installing all of them into the pipx-managed ansible environment so they share the same Python interpreter as ansible-core (avoiding mismatches such as “lint using core 2.18 but running with core 2.21”):

pipx inject --include-apps ansible ansible-lint molecule "molecule-plugins[docker]" ansible-navigator ansible-builder
# You can also use the official all-in-one package: pipx install ansible-dev-tools (includes lint/molecule/navigator/builder, etc.)
ansible-lint --version
molecule --version
ansible-navigator --version
ansible-builder --version
ansible-lint 26.11.0 using ansible-core:2.21.5 ansible-compat:… ruamel-yaml:… ruamel-yaml-clib:…
molecule 26.11.0 using python 3.12
    ansible:2.21.5
    default:26.11.0 from molecule
    docker:26.11.0 from molecule_plugins requiring collections: community.docker>=…
ansible-navigator 26.11.0
3.2.0
Python version ansible-core 2.21 requires control node Python 3.12–3.14; molecule 26.x requires ≥ 3.11, ansible-builder 3.2 requires ≥ 3.11, and ansible-lint/navigator require ≥ 3.10. Ubuntu 24.04 ships with Python 3.12, which meets all requirements.

Warm-up: answer from memory (30 seconds)

When Ansible runs a task, what happens between the control node and the managed node?

The control node renders the task arguments (Jinja2), packages the module code and arguments into an AnsiballZ archive, and sends it over SSH to a temp directory on the managed node (with pipelining enabled, it is passed straight to the remote Python via stdin). The remote Python runs the module and returns JSON, and the control node decides based on the changed/failed field whether to show ok / changed / failed. The role, variables, and Vault in this lesson all take effect before or during this “rendering” step.

When does a handler run?

Notified by notify and the task result is changed, it is queued; by default it runs once at the end of each play’s task sections (pre_tasks, roles + tasks, post_tasks), and can be triggered early with meta: flush_handlers . Module 1 shows that handlers in roles follow the same rule.

When the same variable is set both in the play’s vars: and passed in via -e , which one takes effect?

-e (extra vars) always has the highest precedence. Module 3 covers the full 22-level precedence order.

Production-readiness self-assessment (8 items)

Tick off the current state of your myapp automation: what is already achieved for the project (results are saved in this browser). Revisit after completing the capstone lab.

Environment self-check list

Module 1 · Role structure and reuse

00:00 – 08:00 · Turn “one long playbook” into “several single-responsibility, testable, reusable roles”
8 minansible-core 2.21argument_specs since 2.11★★★★★
Learning objectives
  • Be able to recite the standard role directory layout (tasks / handlers / defaults / vars / templates / files / meta), and explain who loads each directory and when it is loaded automatically.
  • Distinguish defaults/ (lowest precedence, for users to override) from vars/ (high precedence, role-internal constants), and use meta/argument_specs.yml to make wrong arguments fail before the first task.
  • Be able to choose as needed among roles:,import_role, and include_role , and explain the differences in when / tags / loop / handlers that come from “static imports are expanded at parse time, dynamic includes are expanded at runtime.”
Prerequisites: Lesson 1’s play / task / handler / template. Importance:★★★★★ (all later lessons organize work by role)

What: what a role is

Role A role is Ansible’s “directory layout by convention”: put tasks, variables, templates, and handlers into the agreed subdirectories, and Ansible automatically loads the matching main.yml (or main.yaml,main). No include statements are needed. A role usually does one thing (installs and configures Redis, deploys myapp) and can be reused across multiple playbooks and teams, or packaged into a collection for distribution.

DirectoryContentsWhen loadedTypical use
tasks/main.ymlTask list (entry point)When the role runsCan be further split with import_tasks / include_tasks into sub-files; tasks_from: can select other entry points via
handlers/main.ymlHandlersWhen the role is added to a playRestart services; handlers are visible across the whole play
defaults/main.ymlDefault variablesWhen the role is added to a playLowest precedence (level 2 of the 22), reserved for users to override
vars/main.ymlRole variablesWhen the role is added to a playHigh precedence (level 15); for OS package names, internal paths, and other constants that should not be overridden by inventory
templates/,files/Jinja2 templates, static filesReferenced by the template/copy modulessrc: app.py Automatically searched for in the role’s files/ directory
meta/main.ymlgalaxy_info,dependenciesallow_duplicatesWhen the role is added to a playDeclares dependent roles (run before this role)
meta/argument_specs.ymlArgument specAutomatically inserts a validation task when the role runsType, required, and allowed-value checks; generates documentation
library/,module_utils/,*_plugins/Modules and plugins embedded in the roleAdded to the search path when the role is usedNew code is recommended to go into a collection (Module 2)

Why: why split into roles

  • Single responsibility, small blast radius: changes to the Redis config only touch roles/redis, so code review and rollback are clearer.
  • Clear interface: defaults + argument_specs form the role’s “API”. Users only need to override myapp_port,myapp_workers, without reading the task implementation.
  • Testable: Molecule (Module 7) creates containers, runs the role, and verifies idempotence, one role at a time.
  • Distributable: roles can be placed in a collection, published to Galaxy or a private Automation Hub, and referenced by version (Module 2).

How: how roles are found and executed

Lookup order: When writing name: myapp , Ansible searches in order: ① the playbook-level roles/ directory, ② roles_path configuration (default ~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles), ③ the playbook’s directory; for an FQCN (such as myorg.platform.myapp) it searches collections; a path can also be given directly.

Three ways to use them:

MethodStatic / dynamicLocationCharacteristics
roles: KeywordStaticPlay levelClassic syntax; execution order: pre_tasks → handlers → roles → tasks → handlers → post_tasks → handlers
ansible.builtin.import_roleStatic (expanded at parse time)Task levelCan be interleaved with other tasks; tags on the task when/tags will be copied to every task in the role; --list-tasks the tasks inside are visible
ansible.builtin.include_roleDynamic (expanded at runtime)Task levelCan loop, and can use runtime variables (facts, register results) to decide the role name; when evaluates the condition only once, at the include itself; tags default apply only to the include statement, so to pass them to inner tasks you need apply: { tags: [...] }

Deduplication: Within one play, a role referenced several times with identical arguments runs only once (e.g., myapp and redis both depend on common, so common runs once). Different arguments, or when meta/main.yml is set in allow_duplicates: true , will cause it to run again.

Argument validation: When meta/argument_specs.yml is defined, Ansible inserts a task named “Validating arguments against arg spec main” before the role’s first task, checking variables with the same rules as module arguments (type, required, choices, elements, etc.). Invalid input fails right away, instead of discovering halfway through that a port was written as a string.

When: which one to use when

  • For roles that must always run → roles: or import_role (static, predictable,--list-tasks / --list-tags can be fully listed).
  • For loops, or for choosing roles based on runtime facts (e.g., by ansible_facts.os_family including different roles) → include_role.
  • To reuse only part of a role → include_role: { name: myapp, tasks_from: config }.
  • For prerequisites that other roles should pull in automatically (such as common) → meta/main.yml the dependencies meta dependencies, but avoid overusing them: deep dependency chains make execution order hard to infer, so many teams prefer to list them explicitly in the playbook.

Comparison with similar technologies

Ansible roleTerraform moduleHelm chartChef cookbook / Puppet module
Interfacedefaults + argument_specsvariable / outputvalues.yaml + values.schema.jsonattributes / class parameters
Dependenciesmeta dependencies, collectionsmodule source + versionChart.yaml dependenciesmetadata.rb depends
DistributionGalaxy / Automation Hub (mostly within collections)RegistryOCI / chart repoSupermarket / Forge
TestingMoleculeterraform testhelm test / chart-testingTest Kitchen / rspec-puppet
Common misconceptions① “A role’s variables are only visible inside the role” — this is wrong: roles: and import_role loaded defaults/vars are exposed by default to later tasks and roles in the play; only include_role does not expose them by default (can be changed with public: true ). This is the root of variable conflicts, so prefix with the role name. ② “Just put constants in defaults” — values in defaults can be overridden by any inventory variable; constants that must not be overridden belong in vars/. But putting values users need to adjust into vars/ means they can only be overridden with extra vars, which is awkward. ③ “Adding tags to include_role makes --tags select the tasks inside it” — it does not, unless you use apply, or add the same tags to the inner tasks too (Module 6).

Structure diagram: the refactored ~/ansible-lab project

~/ansible-lab/ ansible.cfg requirements.yml ← Module 2 site.yml inventory/hosts.ini inventory/group_vars/all/main.yml inventory/group_vars/all/vault.yml ← Module 4 inventory/group_vars/app.yml ← Module 3 inventory/host_vars/node3.yml roles/common/ roles/redis/ roles/myapp/ molecule/myapp/ ← Module 7 .ansible-lint ← Module 7 execution-environment.yml ← Module 8 roles/myapp/ defaults/main.ymlmyapp_port: 5000 · precedence 2 (lowest) vars/main.ymlmyapp_packages · precedence 15 tasks/main.ymlimport_tasks: install / config / service handlers/main.ymlRestart myapp (visible at play level) templates/myapp.service.j2 · myapp.env.j2 files/app.py meta/main.ymldependencies: [common] meta/argument_specs.ymlType / required check README.md · tests/ (generated by ansible-galaxy; can be deleted in favor of Molecule)Convention over configuration: as long as the file is named main.yml, Ansible loads it automatically
Figure 1-1 Role directory conventions: defaults for users to override, vars for internal constants, meta for dependencies and interface

Flowchart: execution order of roles within a play

gather_factssetup module pre_tasks+ flush handlers Dependent rolecommon (meta dependency,deduplicated, runs only once) roles: myapp① Argument validation task② tasks/main.yml tasks:including import/include_role handlersRestart myapp post_tasks+ handlers Parse time (when ansible-playbook reads the YAML) roles: / import_role / import_tasks are expanded into concrete tasks when / tags are copied to each child task Can only use variables available at parse time, such as play vars and extra vars Runtime (when the task executes, per host) include_role / include_tasks read the file only at this point Can loop, and can use facts and register results when is evaluated only once; inner tasks do not inherit tags (unless apply is used)
Figure 1-2 Execution order within a play, and the points in time at which “static import vs dynamic include” takes effect

Step-by-step animation: how import_role (static) and include_role (dynamic) differ

Same play: - import_role/include_role: name=myapp, with tasks tagged when: deploy_enabled | bool and tags: [app], the run command is ansible-playbook site.yml --tags app. Choose a mode, then step through to see what happens at parse time and at runtime.

Written in the playbook
Task list seen by the executor

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-galaxy role init NAMECreate a role from the standard skeleton--init-path roles Specify the parent directory; --role-skeleton DIR Use a team-custom skeleton
ansible-galaxy role listList roles findable in roles_path-p roles Specify a path
ansible-doc -t role -l / ansible-doc -t role NAMEList roles and view the documentation generated from argument_specs-r roles Specify the role search directory
ansible-playbook site.yml --list-tasksDoes not execute; lists the expanded tasksStatically imported tasks are visible; dynamically included ones only show the include itself
ansible-playbook site.yml --syntax-checkSyntax checkCatches role names that cannot be found and YAML errors
ansible localhost -m ansible.builtin.validate_argument_specCalls the argument validation module directly (used automatically inside a role)Usually no need to call it manually
cd ~/ansible-lab
ansible-galaxy role init myapp --init-path roles
tree roles/myapp
- Role myapp was created successfully
roles/myapp
├── README.md
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

How to verify:ansible-galaxy role list -p roles Can list myapp. Common mistakes: In the roles/ directory, running init again generates roles/roles/myapp; using hyphens in role names (my-app) works, but such a role cannot be placed in a collection (role names in a collection may only contain lowercase letters, digits, and underscores). Production use: The team maintains a --role-skeleton, with built-in .ansible-lint, Molecule scenarios, and argument_specs templates.

ansible-playbook site.yml --list-tasks
ansible-doc -t role -r roles myapp
playbook: site.yml
  play #2 (app): myapp	TAGS: []
    tasks:
      common : Install base packages	TAGS: [common]
      myapp : Validating arguments against arg spec main - Deploy myapp	TAGS: [always]
      myapp : Install OS packages	TAGS: [install]
      ...
> ROLE: *myapp* (/home/azureuser/ansible-lab/roles/myapp)
ENTRY POINT: *main* - Deploy myapp (Flask + gunicorn) as a systemd service
        OPTIONS (= indicates it is required):
= myapp_redis_host  Redis host the app connects to
        type: str
- myapp_port  gunicorn listen port
        default: 5000
        type: int

Note that the argument validation task automatically has the always tag, so it still runs even when using --tags .

Syntax for the three invocation methods

- name: myapp (classic syntax)
  hosts: app
  become: true
  roles:
    - role: myapp
      vars:
        myapp_workers: 4          # role parameter (precedence 20)

- name: myapp (task-level static import, can be interleaved with other tasks)
  hosts: app
  become: true
  tasks:
    - name: Pre-flight check
      ansible.builtin.assert:
        that: ansible_facts.distribution == "Ubuntu"
    - name: Deploy myapp
      ansible.builtin.import_role:
        name: myapp

- name: Dynamically select a role by OS (can only use include)
  hosts: all
  tasks:
    - name: Include OS specific hardening
      ansible.builtin.include_role:
        name: "hardening_{{ ansible_facts.os_family | lower }}"
        apply:
          tags: [hardening]
      tags: [hardening]

Lab 1: Split myapp’s single-file playbook into three roles (about 8 minutes)

Create the role skeleton and delete the unused tests/ (Molecule will replace it later):
cd ~/ansible-lab
for r in common redis myapp; do ansible-galaxy role init $r --init-path roles; rm -rf roles/$r/tests; done
mkdir -p roles/myapp/files roles/myapp/templates
cp files/myapp/app.py roles/myapp/files/   # application code from Lesson 1, Lab 8
ls roles
- Role common was created successfully
- Role redis was created successfully
- Role myapp was created successfully
common  myapp  redis
myapp’s interface: defaults and vars (all variables use the prefix myapp_ ):
---
# Parameters users can override (lowest precedence)
myapp_version: "1.0.0"
myapp_port: 5000
myapp_workers: 2
myapp_user: myapp
myapp_home: /opt/myapp
myapp_redis_host: 127.0.0.1       # safe default; in the lab, group_vars/app.yml points it to the cache group (node1, 172.30.0.11)
myapp_redis_port: 6379
myapp_redis_password: ""          # Module 4 changes this to reference a Vault variable
myapp_healthcheck_path: /healthz
---
# role-internal constants (high precedence; should not be overridden by inventory)
myapp_packages:
  - python3-venv
  - python3-pip
myapp_pip_packages:
  - flask==3.1.*                   # matches the Lesson 1 requirements.txt
  - redis==5.*
  - gunicorn==23.*
myapp_env_file: /etc/myapp.env
myapp_unit_file: /etc/systemd/system/myapp.service
Split tasks by stage (preparing for the block and tags in Modules 5 and 6):
---
- name: Install
  ansible.builtin.import_tasks: install.yml
  tags: [install]

- name: Configure
  ansible.builtin.import_tasks: config.yml
  tags: [config]

- name: Service
  ansible.builtin.import_tasks: service.yml
  tags: [service]
---
- name: Install OS packages
  ansible.builtin.apt:
    name: "{{ myapp_packages }}"
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Create service user
  ansible.builtin.user:
    name: "{{ myapp_user }}"
    system: true
    shell: /usr/sbin/nologin
    home: "{{ myapp_home }}"
    create_home: false

- name: Create application directory
  ansible.builtin.file:
    path: "{{ myapp_home }}"
    state: directory
    owner: "{{ myapp_user }}"
    group: "{{ myapp_user }}"
    mode: "0755"

- name: Deploy application code
  ansible.builtin.copy:
    src: app.py
    dest: "{{ myapp_home }}/app.py"
    owner: "{{ myapp_user }}"
    group: "{{ myapp_user }}"
    mode: "0644"
  notify: Restart myapp

- name: Install Python dependencies into venv
  ansible.builtin.pip:
    name: "{{ myapp_pip_packages }}"
    virtualenv: "{{ myapp_home }}/venv"
    virtualenv_command: python3 -m venv
---
- name: Render environment file
  ansible.builtin.template:
    src: myapp.env.j2
    dest: "{{ myapp_env_file }}"
    owner: root
    group: "{{ myapp_user }}"
    mode: "0640"
  diff: false                     # the file contains a password, so do not show it in --diff
  notify: Restart myapp

- name: Render systemd unit
  ansible.builtin.template:
    src: myapp.service.j2
    dest: "{{ myapp_unit_file }}"
    owner: root
    group: root
    mode: "0644"
  notify: Restart myapp
---
- name: Enable and start myapp
  ansible.builtin.systemd_service:
    name: myapp
    state: started
    enabled: true
    daemon_reload: true
---
- name: Restart myapp
  ansible.builtin.systemd_service:
    name: myapp
    state: restarted
    daemon_reload: true
# {{ ansible_managed }}
REDIS_HOST={{ myapp_redis_host }}
REDIS_PORT={{ myapp_redis_port }}
REDIS_PASSWORD={{ myapp_redis_password }}
APP_VERSION={{ myapp_version }}
# {{ ansible_managed }}
[Unit]
Description=myapp (Flask + gunicorn) {{ myapp_version }}
After=network-online.target
Wants=network-online.target

[Service]
User={{ myapp_user }}
Group={{ myapp_user }}
EnvironmentFile={{ myapp_env_file }}
WorkingDirectory={{ myapp_home }}
ExecStart={{ myapp_home }}/venv/bin/gunicorn --bind 0.0.0.0:{{ myapp_port }} --workers {{ myapp_workers }} --access-logfile - app:app
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target

Lesson 1’s app.py only reads REDIS_HOST (the port is hard-coded to 6379). To support the Module 4 Redis password, change roles/myapp/files/app.py in the connection statement to redis.Redis(host=os.getenv("REDIS_HOST","redis"), port=int(os.getenv("REDIS_PORT","6379")), password=os.getenv("REDIS_PASSWORD") or None).

meta: dependencies and argument specs
---
galaxy_info:
  author: platform-team
  description: Deploy myapp (Flask + gunicorn) as a systemd service
  license: MIT
  min_ansible_version: "2.20"
  platforms:
    - name: Ubuntu
      versions: [noble]
dependencies:
  - role: common
---
argument_specs:
  main:
    short_description: Deploy myapp (Flask + gunicorn) as a systemd service
    options:
      myapp_port:
        type: int
        default: 5000
        description: gunicorn listen port
      myapp_workers:
        type: int
        default: 2
        description: Number of gunicorn workers
      myapp_redis_host:
        type: str
        required: true
        description: Redis host the app connects to
      myapp_redis_password:
        type: str
        no_log: true
        description: Redis password (store it in Ansible Vault)
      myapp_version:
        type: str
        default: "1.0.0"
        description: Release label shown by the app

The values in argument_specs default are only used for documentation and validation; the real default values still come from defaults/main.yml, and the two must stay consistent (ansible-lint will not compare them for you).

redis and common roles (common uses collection modules, which Module 2 installs):
---
redis_bind: "0.0.0.0 ::"
redis_port: 6379
redis_password: ""
redis_maxmemory: 128mb
---
- name: Install redis-server
  ansible.builtin.apt:
    name: redis-server
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Configure redis
  ansible.builtin.lineinfile:
    path: /etc/redis/redis.conf
    regexp: "^#?\\s*{{ item.key }}\\s"
    line: "{{ item.key }} {{ item.value }}"
  loop:
    - { key: bind, value: "{{ redis_bind }}" }
    - { key: port, value: "{{ redis_port }}" }
    - { key: protected-mode, value: "{{ 'yes' if redis_password | length > 0 else 'no' }}" }
    - { key: requirepass, value: "{{ redis_password }}" }
    - { key: maxmemory, value: "{{ redis_maxmemory }}" }
  loop_control:
    label: "{{ item.key }}"        # do not print the value (it contains the password)
  when: item.key != 'requirepass' or redis_password | length > 0
  notify: Restart redis

- name: Enable and start redis
  ansible.builtin.systemd_service:
    name: redis-server
    state: started
    enabled: true
---
- name: Restart redis
  ansible.builtin.systemd_service:
    name: redis-server
    state: restarted
---
- name: Install base packages
  ansible.builtin.apt:
    name: [curl, ca-certificates, tzdata]
    state: present
    update_cache: true
    cache_valid_time: 3600
  tags: [common]

- name: Set timezone
  community.general.timezone:
    name: "{{ common_timezone }}"
  tags: [common]

- name: Authorize ops SSH keys
  ansible.posix.authorized_key:
    user: "{{ ansible_user }}"
    key: "{{ item }}"
  loop: "{{ common_ops_ssh_keys }}"
  tags: [common]
---
common_timezone: America/Toronto
common_ops_ssh_keys: []

Note: in when the conditional uses redis_password | length > 0 expressions like this one must return a boolean; from ansible-core 2.19 onward,when: redis_password (a string) raises “Conditionals must have a boolean result”.

New site.yml:
---
motd_role: app
myapp_port: 5000
myapp_workers: 2
myapp_redis_host: "{{ hostvars[groups['cache'][0]]['ansible_host'] }}"   # 172.30.0.11
# Lesson 1’s old variable names are no longer used
sed -i '/^app_port:/d' inventory/group_vars/all.yml
sed -i 's/^gunicorn_workers:/myapp_workers:/' inventory/host_vars/node3.yml
# the nginx template now reads the new variable names
sed -i "s/hostvars\[h\]\['app_port'\]/hostvars[h]['myapp_port']/" templates/nginx-myapp.conf.j2
cp site.yml legacy-site-v1.yml        # keep the Lesson 1 version; Module 7 uses it to compare lint results
---
- name: Redis (cache tier)
  hosts: cache
  become: true
  roles:
    - role: redis

- name: myapp (app tier)
  hosts: app
  become: true
  roles:
    - role: myapp

- name: nginx load balancer (lb tier, tasks unchanged from lesson 1)
  hosts: lb
  become: true
  tasks:
    - name: Ensure nginx is installed
      ansible.builtin.apt:
        name: nginx
        state: present
    - name: Render upstream config
      ansible.builtin.template:
        src: nginx-myapp.conf.j2
        dest: /etc/nginx/conf.d/myapp.conf
        mode: "0644"
      notify: Reload nginx
    - name: Remove default site
      ansible.builtin.file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      notify: Reload nginx
    - name: Validate nginx config
      ansible.builtin.command: nginx -t
      changed_when: false
    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

The nginx layer keeps Lesson 1’s approach for now (only the task-name casing changed to satisfy lint); turning it into a role is left as an exercise, and Lesson 6 will expand it into a multi-tier architecture. The “gather facts” and “end-to-end verification” plays in Lesson 1’s site.yml are no longer needed in this lesson: myapp_redis_host depends only on the inventory ansible_host; end-to-end verification is now done by the Module 6 smoke tasks and the Module 7 Molecule tests.

ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --list-tasks | head -30
# Before Module 2 installs the collection, community.general.timezone in common will error — skip it for now:
ansible-playbook site.yml --skip-tags common
playbook: site.yml
...
TASK [myapp : Validating arguments against arg spec main - Deploy myapp (Flask + gunicorn) as a systemd service] ***
ok: [node3]
ok: [node2]
...
PLAY RECAP *********************************************************************
node3  : ok=11  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
node2  : ok=11  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
node1  : ok=4   changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

The first run shows changed because the unit file and env file content/paths changed (added ansible_managed comments and EnvironmentFile). Running again must show changed=0— this is the most basic proof that the refactor introduced no side effects.

Verify argument validation: deliberately pass a wrong type:
ansible-playbook site.yml --limit node3 --skip-tags common -e myapp_port=abc
TASK [myapp : Validating arguments against arg spec main - Deploy myapp ...] ***
fatal: [node3]: FAILED! => {"argument_errors": ["argument 'myapp_port' is of type str and we were unable to convert to int: ..."],
 "changed": false, "msg": "Validation of arguments failed:\nargument 'myapp_port' is of type str and we were unable to convert to int: ..."}

It fails before the first real task, and the managed nodes are not changed at all. Cleanup: this lab needs no cleanup; keep all files for later modules.

Case 1: the same role “copy-pasted” by three teams

Problem: The nginx configuration task exists in three repositories; when the security team requires unified TLS parameters, three places must be changed, and one gets missed. Approach: Extract it into a nginx role in an internal collection myorg.platform, define parameters such as nginx_tls_protocols with argument_specs, and have the three repositories reference a pinned version in requirements.yml . Configuration: The role’s defaults use a secure baseline; teams only override site-specific parameters. Limits: version upgrades need a release process (Module 2); once published, a role’s interface must stay compatible like an API, and parameters must be deprecated before they are removed. Case 2: meta dependencies cause “invisible execution”

Problem:

A role lists the role as a dependency in meta, which depends on the java role; the team then listed repo again explicitly in the playbook java with different arguments, so java ran twice and the second run changed the JDK version back. Approach: Limit dependency chains to one level; when different arguments are needed, use an explicit include_role In CI, use --list-tasks to output the task list as a review attachment. Limits: role de-duplication only applies to “identical arguments”; this is the correct design but easy to overlook.

Case 3: dynamic include slows execution across a large number of hosts

Problem: On 2000 hosts, a loop uses include_role, where every iteration loads a file at runtime and generates tasks for each host, so execution takes twice as long as with a static import. Approach: Where no runtime decision is needed, change it to import_role; where it must be dynamic, move the loop inside the role (one include, multiple loop tasks). Limits: Static import cannot use inventory or facts variables to decide the role name.

Common errors and fixes

ERROR! the role 'myapp' was not found in /home/azureuser/ansible-lab/roles:/home/azureuser/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:/home/azureuser/ansible-lab

Cause: The role directory is not on the search path, or the name is spelled inconsistently (casing, hyphens vs underscores). When running the playbook from another directory,roles/ relative paths are resolved against the directory of the playbook file, not the current directory.

ansible-config dump --only-changed | grep -i roles
ansible-galaxy role list -p roles
ls -d roles/*/

Fix: Correct the name; or set roles_path = ./roles in ansible.cfg; or use the FQCN from a collection.

ERROR! The requested handler 'restart myapp' was not found in either the main handlers list nor in the listening handlers list

Cause: The handler name casing does not match (Lesson 1 called it restart myapp, but the role uses Restart myapp); or the handler is defined in a include_role that has not been included yet.

grep -rn "notify\|name: .*[Rr]estart" roles/myapp

Fix: Unify the names; for cross-role notification, use listen: topics (such as listen: myapp config changed); handlers in a dynamically included role only exist after the include runs.

Validation of arguments failed: missing required arguments: myapp_redis_host

Cause: A variable marked required in argument_specs has no value. Note that values in defaults count as having a value, so the error only appears when defaults has no value either.

ansible-doc -t role -r roles myapp
ansible-inventory --host node3 | grep myapp_

Fix: Provide the variable in group_vars; or, if it really should have a default, add it to defaults and remove required.

[WARNING]: Could not match supplied host pattern … / task ran twice: myapp : Install OS packages appears twice

Cause: The role was referenced twice with different arguments (for example roles: [{role: myapp}, {role: myapp, vars: {myapp_port: 8080}}]), or allow_duplicates: true was set in meta.

Fix: Confirm whether multiple instances are really needed; if so (for example, two instances on the same host), make the role accept an instance-name parameter (myapp_instance), and make sure file paths and service names include the instance name.

conflicting action statements: import_role, tags / 'apply' is not a valid attribute for a IncludeRole/ImportRole

Cause: An indentation error made tags be parsed as module parameters, or import_role an option was used on include_role that is only supported by apply.

Fix:apply Use only with include_role/include_tasks; import itself passes tags/when to all child tasks, so apply is not needed. Tags should be indented at the same level as the module name.

Command-line practice questions
1. In roles/ , create a role named nginx and view the parameter documentation for the myapp role.
ansible-galaxy role init nginx --init-path roles
ansible-doc -t role -r roles myapp
2. Run only the config.yml tasks in the myapp role (without changing the role code).
- hosts: app
  become: true
  tasks:
    - name: Only configuration
      ansible.builtin.include_role:
        name: myapp
        tasks_from: config

Or use the tags already set up in the lab: ansible-playbook site.yml --tags config (Module 6).

Scenario analysis
A team wants a playbook that calls the myapp role once per “tenant” (different ports, different users), with the tenant list coming from the inventory variable tenants. Should they use roles:, import_role, or include_role? What else in the role needs to change?

A loop is needed and the loop data comes from inventory (only known at runtime), so only include_role + loop: "{{ tenants }}" + vars: { myapp_port: "{{ item.port }}", ... } can be used (loop_control’s loop_var avoids conflicts with the item inside the role). The role needs to support the concept of an “instance”: the service name, unit file, env file, and install directory all include the instance name (for example myapp-{{ myapp_instance }}), and handlers must also restart per instance, otherwise the instances overwrite each other.

Verified teaching videos

▶
Ansible 101 - Episode 6 - Ansible Vault and Roles — Jeff Geerling
2020 livestream series · English · about 1 hour · the second half explains how to refactor a playbook into roles (recorded in the Ansible 2.9 era; for newer syntax such as FQCN and argument_specs, follow this lesson)

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 files directly. A storyboard and narration script are provided for a video tool.

Shot 1 · 0–15s
Visual: a 200-line site.yml scrolls on screen, with red boxes marking hard-coded variables and duplicate tasks.
Narration: a playbook that works is often a file that keeps growing. Change one spot, and you have to understand all of it.
Shot 2 · 15–40s
Visual: the file is “split apart”; tasks fly into tasks/, variables fly into defaults/ and vars/, templates fly into templates/, forming the role directory tree.
Narration: a role is a directory organized by convention. defaults holds parameters for users to override, vars holds internal constants, and meta declares dependencies and argument specs.
Shot 3 · 40–70s
Visual: on the left, import_role is expanded at “parse time” into five tasks, each tagged with when and tags; on the right, include_role is expanded only at “runtime”, and only the entry point carries the tag.
Narration: static imports are expanded when the playbook is read, and conditions and tags are copied to each child task; dynamic includes are expanded when execution reaches that line. They can loop, but tags are not passed down by default.
Shot 4 · 70–90s
Visual: the terminal runs ansible-playbook; the first line shows Validating arguments against arg spec, followed by PLAY RECAP changed=0.
Narration: argument specs expose errors before the first task; after the refactor, run it again, and changed must be zero.
or score 70% or higher on the quiz

Module 2 · Collections and ansible-galaxy

08:00 – 14:00 · The distribution unit for modules, plugins, and roles; use FQCN to make clear “whose module it is”, and requirements.yml to make clear “which version is used”
6 mincommunity.general 14.0.1 · ansible.posix 2.2.2★★★★☆
Learning objectives
  • Explain collection naming (namespace.collection) and FQCN (namespace.collection.plugin), and know that ansible-core ships only ansible.builtin, while the community package ansible 14.x preinstalls about a hundred collections.
  • Write a requirements.yml with version constraints, install collections into the project ./collections, and use ansible-galaxy collection list to determine which version is actually loaded.
  • Understand offline installation (download → tarball), signature and integrity verification (verify), and private Automation Hub configuration.
Prerequisites: Module 1’s roles. Importance:★★★★☆ (the number one cause of “the same playbook behaves differently on two machines”)

What: what a collection is

Collection is the packaging and distribution format for Ansible content (since Ansible 2.10). A collection can contain modules, various plugins (lookup, filter, inventory, callback, connection, …), roles, playbooks, and docs, and is published as namespace-name-version.tar.gz to Ansible Galaxy, Red Hat Automation Hub, or a private Galaxy (Pulp / Private Automation Hub).

TermExampleDescription
namespacecommunity,ansible,azure,amazonpublisher namespace
collectioncommunity.general,ansible.posixdistribution and versioning unit (semantic versioning)
FQCNcommunity.general.timezoneFully Qualified Collection Name: namespace.collection.plugin_name
ansible.builtinansible.builtin.copyShipped with ansible-core; its version is the core version
ansible.legacyShort name copy actually resolves to ansible.legacy.copy= ansible.builtin + local library/ same-named modules in directories such as ..., which may be overridden by name

Why: why FQCN and version pinning are needed

  • Remove ambiguity: A short name timezone may come from community.general, or from another collection or a local library directory. FQCN lets reviewers and Ansible alike know exactly which one it is.
  • Reproducible: The community package ansible upgrades the collections inside it with each major version (which may include breaking changes). If control node A has Ansible 13 and B has 14, the same playbook can behave differently. Pinning inside the project requirements.yml + ./collections keeps versions tied to the code.
  • Minimal: A production EE (Module 8) usually installs only ansible-core plus the few collections it needs, rather than the full 300 MB community package.

How: the order in which Ansible looks up collections

  1. playbook-adjacent directory: <playbook directory>/collections/ansible_collections/ (highest precedence; suitable for project-pinned versions).
  2. collections_path Configuration (ansible.cfg [defaults] collections_path, environment variable ANSIBLE_COLLECTIONS_PATH), default ~/.ansible/collections:/usr/share/ansible/collections.
  3. Python sys.path in the ansible_collections package (collections_scan_sys_path, enabled by default): the community package installed via pip/pipx ansible places its collections here.

First match wins: if the project installs community.general 14.0.1 and the community package ships 12.x, then 14.0.1 is used at runtime. ansible-galaxy collection list lists the paths separately; when the same collection appears in several paths, the first path in the list takes precedence.

During installation:ansible-galaxy reads requirements.yml → queries the configured Galaxy server ([galaxy] server_list, default galaxy.ansible.com) for version metadata → resolves dependencies (the galaxy.yml declared in the collection’s dependencies) → downloads the tarball and verifies its SHA256 (optional GPG signature) → extracts it to <path>/ansible_collections/<namespace>/<name>/, and writes MANIFEST.json,FILES.json.

Version constraint syntax

FormatMeaningUse case
"2.2.2" or "==2.2.2"exact versionproduction, EE builds (recommended)
">=14.0.0,<15.0.0"latest within the same major versiondevelopment environments; combine with periodic upgrades
"*" (default)Any latest versionOnly suitable for experiments
"!=14.0.0"Exclude a problematic versionTemporary workaround

ansible-galaxy has no native lock file. For full reproducibility: in production, write exact versions for everything in requirements.yml, or build the entire collections/ directory into the EE image (Module 8).

When: when to use which installation method

  • Learning and temporary scripts: use the community package directly ansible with its bundled collections.
  • Team projects: requirements.yml + ansible-galaxy collection install -r requirements.yml -p ./collections,collections/ add it to .gitignore (or, in small teams, commit it to support offline use).
  • Production and CI: hand requirements.yml to ansible-builder to build the EE, so everyone and AWX/AAP use the same image (Module 8, Lesson 5).
  • Isolated internal networks: ansible-galaxy collection download Produce a tarball + requirements.yml, copy them into the internal network, then install --offline, or set up a Private Automation Hub.

Comparison with similar technologies

Ansible collectionTerraform providerPython packages
Dependency declarationrequirements.ymlrequired_providersrequirements.txt / pyproject
Lock fileNo native lock file (exact versions or EE).terraform.lock.hclpip-tools / uv.lock
Install locationProject collections/ or user directory.terraform/providersvenv site-packages
IntegritySHA256 + optional GPG signature (verify)Hash + signatureHash (--require-hashes)
Common misconceptions① “Using the collections: keyword means short names are allowed” — they are, but ansible-lint’s fqcn rule will warn, and same-named plugins still cause ambiguity, so always write FQCNs. ② “ansible.builtin also needs to be installed” — no, it is ansible-core itself; but all the other modules (including ansible.posix.synchronize,community.general.ufw) are missing if only ansible-core is installed. ③ “ansible-galaxy install upgrades installed collections by default” — no, already-installed ones are skipped; to upgrade, use --upgrade (or --force reinstall).

Architecture diagram: collection sources and the search path

galaxy.ansible.comPublic community collections Automation Hub / PAHCertified content · private content Git repository / tarballtype: git / file / url ansible-galaxyRead requirements.ymlResolve dependencies · verify SHA256 ① ./collections/ansible_collectionsNext to playbook · community.general 14.0.1 ② collections_path~/.ansible/collections · /usr/share/ansible/collections ③ ansible_collections in Python sys.pathBundled with the community package ansible 14.x (may be an older version) -p ./collections At runtime, community.general.timezone is looked up in the order ① → ② → ③; the first match wins
Figure 2-1 Three sources → ansible-galaxy install → loaded at runtime in search-path order

Flowchart: how a task’s module name is resolved

Module name in the taskapt / x.y.apt Contains two dots: FQCNLocates namespace.collection directly Short nameChecked against the collections: list + ansible.legacy meta/runtime.ymlplugin_routing: redirect / deprecate / remove Not foundcouldn't resolve module/action Load the module codePackage AnsiballZ → SSH
Figure 2-2 FQCN locates the module directly; short names depend on the collections keyword and ansible.legacy, which can cause ambiguity

Step-by-step animation: from requirements.yml to module execution

Choose a scenario, then step through it. The terminal shows the real command or Ansible output for each step.

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-galaxy collection install -r requirements.yml -p ./collectionsInstall into the project directory from a file-U/--upgrade upgrade; --force reinstall; --no-deps; --pre allow pre-releases; --offline
ansible-galaxy install -r requirements.ymlinstall both at the same time roles: and collections: two partsroles are installed into the first entry of roles_path, collections into the first entry of collections_path
ansible-galaxy collection listList the installed collections and their versions in each pathCan filter by name: list community.general; --format json
ansible-galaxy collection download -r requirements.yml -p ./offlineDownload tarballs for offline installationalso generates offline/requirements.yml
ansible-galaxy collection verify NAMECompare local files against server checksums--offline Use the local MANIFEST only; --signature,--keyring
ansible-doc community.general.timezoneView module documentation and examples-l community.general List the modules in this collection
ansible-config dump | grep -i collectionView the collections_path that is actually in effect--only-changed
---
collections:
  - name: community.general
    version: ">=14.0.0,<15.0.0"     # Development: within the same major version
  - name: ansible.posix
    version: "2.2.2"                 # Production: exact version
  - name: community.docker           # used by the Module 7 Molecule create.yml
    version: "5.4.0"
# Examples of other sources:
#  - name: https://github.com/myorg/platform-collection.git
#    type: git
#    version: v1.3.0
#  - name: ./dist/myorg-platform-1.3.0.tar.gz
#    type: file
[defaults]
collections_path = ./collections:~/.ansible/collections:/usr/share/ansible/collections
roles_path = ./roles
ansible-galaxy collection install -r requirements.yml -p ./collections
ansible-galaxy collection list community.general
Starting galaxy collection install process
Process install dependency map
Starting collection install process
Downloading https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/artifacts/community-general-14.0.1.tar.gz to /home/azureuser/.ansible/tmp/...
Installing 'community.general:14.0.1' to '/home/azureuser/ansible-lab/collections/ansible_collections/community/general'
community.general:14.0.1 was installed successfully
Installing 'ansible.posix:2.2.2' to '/home/azureuser/ansible-lab/collections/ansible_collections/ansible/posix'
ansible.posix:2.2.2 was installed successfully
...

# /home/azureuser/ansible-lab/collections/ansible_collections
Collection        Version
----------------- -------
community.general 14.0.1

# /home/azureuser/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible_collections
Collection        Version
----------------- -------
community.general 12.x.x

How to verify: When the same collection is listed twice, the first path segment (in the project) takes precedence; you can also run ansible -m community.general.timezone -a name=UTC node3 --check -vvv, and in the -vvv output, see the module’s load path. Common errors: If -p specifies a directory that is not in collections_path, ansible-galaxy warns “the collection will not be picked up”. Production use: The first step in CI is ansible-galaxy collection install -r requirements.yml, to make sure tests and runs use the same version. The version bundled with the community package depends on the patch version of the Ansible 14.x you install; the 12.x.x above is only illustrative.

Offline and private servers

# On a machine with internet access
ansible-galaxy collection download -r requirements.yml -p ./offline
tar czf collections-offline.tgz offline/
# On the control node inside the internal network
tar xzf collections-offline.tgz
ansible-galaxy collection install -r offline/requirements.yml -p ./collections --offline
[galaxy]
server_list = private_hub, release_galaxy

[galaxy_server.private_hub]
url = https://hub.example.internal/api/galaxy/content/published/
token = injected from the environment variable ANSIBLE_GALAXY_SERVER_PRIVATE_HUB_TOKEN; do not commit it to Git

[galaxy_server.release_galaxy]
url = https://galaxy.ansible.com/

Each [galaxy_server.NAME] setting can be provided by the environment variable ANSIBLE_GALAXY_SERVER_<NAME>_<KEY> , and CI uses it to inject the token.

Lab 2: install a collection into the project and get the common role running (about 5 minutes)

Write requirements.yml and configure ansible.cfg (see the “Commands” page for the content), then install:
cd ~/ansible-lab
ansible-galaxy collection install -r requirements.yml -p ./collections
echo "collections/" >> .gitignore
ansible-galaxy collection list | grep -E "^#|community.general|ansible.posix|community.docker"
Confirm that the module resolves to the project version:
ansible-doc community.general.timezone | head -5
ansible node3 -m community.general.timezone -a "name=America/Toronto" --check -vvv 2>&1 | grep -i "collections/ansible_collections/community/general" | head -2
> MODULE community.general.timezone (/home/azureuser/ansible-lab/collections/ansible_collections/community/general/plugins/modules/timezone.py)
...
Using module file /home/azureuser/ansible-lab/collections/ansible_collections/community/general/plugins/modules/timezone.py
Add common to the playbook and run it in full (no longer skipping the common tag):
ansible-playbook site.yml
ansible all -m ansible.builtin.command -a "timedatectl show -p Timezone --value"
TASK [common : Set timezone] ***************************************************
changed: [node3]
changed: [node2]
...
node3 | CHANGED | rc=0 >>
America/Toronto

Note that common only runs on the app group (pulled in via myapp’s meta dependency); node1 does not have it. To have all hosts run common, add a hosts: all play at the top of site.yml that calls it explicitly — this is more intuitive than a dependency chain. If the timezone task fails with timedatectl in a container, confirm the node runs with systemd as PID 1 (Module 0).

Experience “short-name ambiguity”: temporarily change the community.general.timezone in the common tasks to timezone and run ansible-playbook site.yml --syntax-check, observe the error (see the first entry on the Troubleshooting page), then change it back to the FQCN.
Integrity check:
ansible-galaxy collection verify ansible.posix -p ./collections
Successfully verified that checksums for 'ansible.posix:2.2.2' match the remote collection.

If someone “temporarily changed” a file in the collection, verify lists the modified files. Cleanup: none needed.

Case 1: the playbook suddenly failed after a community package upgrade

Problem: An engineer on a new control node pipx install ansible got 14.x, a parameter of a community.general module was removed in the new major version, and the nightly job failed; the old control node was still on 12.x, where everything worked. Approach: The project adds requirements.yml with exact versions, and CI and all control nodes run install first; collection upgrades go through the change process, and their changelog “Breaking Changes / Removed Features” must be read. Limits: Exact versions need someone to upgrade them periodically, or security fixes will be missed — use tools like Renovate/Dependabot, or scheduled tasks that open PRs.

Case 2: an air-gapped network for a financial customer

Problem: The control node cannot access the internet. Approach: Set up a Private Automation Hub in the DMZ and sync the allowlisted collections from Automation Hub and Galaxy; the internal ansible.cfg’s server_list setting points only to the private Hub; the final deliverable is an EE image, pushed to the internal image registry. Limits: Requires an AAP subscription; teams without one can use the download/tarball approach, or the community’s galaxy_ng.

Case 3: an internal collection that unifies platform capabilities

Problem: Each team wrote its own Redis, nginx, and monitoring-agent roles. Approach: The platform team publishes a myorg.platform collection (ansible-galaxy collection init myorg.platform), moves the roles into roles/, puts custom filters into plugins/filter/, and publishes to the private Hub with semantic versioning; business repositories reference it in requirements.yml. Limits: Role names in a collection cannot contain hyphens; when referencing them, write myorg.platform.redis.

Common errors and fixes

ERROR! couldn't resolve module/action 'timezone'. This often indicates a misspelling, missing collection, or incorrect module path.

Cause: A short name was used and no available collection provides it, or the collection was never installed into the search path.

ansible-galaxy collection list | grep -i general
ansible-doc -l | grep -w timezone
ansible-config dump | grep -i COLLECTIONS_PATH

Fix: Write the FQCN community.general.timezone; add that collection to requirements.yml and install it; check whether collections_path includes the install directory.

[WARNING]: The specified collections path '/home/azureuser/ansible-lab/vendor' is not part of the configured Ansible collections paths … The installed collection will not be picked up in an Ansible run

Cause:-p The specified directory is not in collections_path (nor is it the playbook-adjacent collections/).

Fix: Use -p ./collections (playbook-adjacent directory), or add the directory to the ansible.cfg collections_path setting.

ERROR! Failed to resolve the requested dependencies map. Could not satisfy the following requirements: * community.general:>=15.0.0 (direct request)

Cause: The version constraint cannot be satisfied (the version does not exist, only pre-releases exist, or it conflicts with another collection’s dependencies).

ansible-galaxy collection install community.general:==99.0.0 2>&1 | tail -3   # the error message lists the available versions

Fix: Relax or correct the constraint; pre-release versions require --pre; for dependency conflicts, check each collection’s galaxy.yml dependency range.

Skipping 'community.general:14.0.1' as it is already installed (but the runtime uses the old version)

Cause: Either it is already installed (without --upgrade , nothing changes), or it was installed into a path with lower precedence, so an older version elsewhere is found first at runtime.

ansible-galaxy collection list community.general

Fix: Check in search order; put the in-project ./collections first in collections_path; when upgrading, add -U.

[DEPRECATION WARNING]: community.general.xxx has been deprecated … This feature will be removed from community.general in version NN.0.0

Cause: The collection marked the module through meta/runtime.yml ’s plugin_routing as deprecated or redirected.

Fix: Migrate to the new module or new collection as the warning says; before upgrading a major version, search the CI logs for DEPRECATION WARNING and use them as an upgrade checklist.

Command-line practice questions
1. Upgrade all collections in requirements.yml to the latest version the constraints allow, and install them into the project directory.
ansible-galaxy collection install -r requirements.yml -p ./collections --upgrade
2. Prepare an offline installation package for a control node that cannot access the internet.
ansible-galaxy collection download -r requirements.yml -p ./offline
# After copying offline/ into the internal network:
ansible-galaxy collection install -r offline/requirements.yml -p ./collections --offline
Scenario analysis
CI passes ansible-lint and ansible-playbook succeeds, but a colleague gets “Unsupported parameters for (community.general.xxx) module” when running it locally. How do you troubleshoot this?

This is a typical version mismatch: CI installed the version in requirements.yml, while the colleague’s machine uses the old version bundled with the community package (or an old version in the user directory ~/.ansible/collections). Have the colleague run ansible-galaxy collection list community.general to see the version in each path, and confirm that the project’s ansible.cfg puts ./collections first in collections_path and that install has been run. Long-term solution: standardize on EEs (Module 8).

Verified teaching videos

▶
Ansible 101 - Episode 13 - Ansible Collections and a Test Plugin — Jeff Geerling
2020 livestream series · English · about 1 hour · explains collection structure, FQCN, and writing plugins in a collection (recorded when collections were new; for search paths and the Galaxy interface, follow this lesson)
▶
Ansible 101 - Episode 7 - Molecule Testing and Linting and Ansible Galaxy — Jeff Geerling
2020 livestream series · English · covers how to use Galaxy requirements files (also a reference for Module 7)

Official docs

Video storyboard (about 75 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: two control nodes run the same playbook; one shows green, the other red, with Unsupported parameters in red.
Narration: the same playbook gives different results on two machines? Most likely the collection versions differ.
Shot 2 · 15–40s
Visual: the module name timezone becomes community.general.timezone, with the namespace, collection, and module each highlighted.
Narration: FQCN makes clear “whose module it is”, removing same-name ambiguity.
Shot 3 · 40–60s
Visual: requirements.yml → ansible-galaxy → ./collections directory; the three layers of the search path are arranged top to bottom, with the first layer lit up.
Narration: requirements pin the version, installation goes into the project directory, and the in-project version is found first at runtime.
Shot 4 · 60–75s
Visual: collection list output shows two path segments, with the first one circled.
Narration: if you suspect the wrong version, run collection list and check which version is in the first path segment.
or score 70% or higher on the quiz

Module 3 · Variable precedence and organization

14:00 – 21:00 · The same variable is defined in 8 places — which one wins? Turn guessing into calculating
7 min22-level precedence (official docs)core 2.19+ stricter templating and conditionals★★★★★
Learning objectives
  • Remember the 8 most commonly used precedence levels (from low to high): role defaults → inventory group_vars/all → group_vars/<group> → host_vars/<host> → play vars → role vars → set_fact / register → extra vars.
  • Know that the group_vars and host_vars in both the inventory directory and the playbook directory group_vars/ are loaded; also know the override rules for parent/child and sibling groups, and that dictionaries are “replaced as a whole” by default rather than merged.
  • Establish a non-conflicting organization: which layer variables go in, role-prefix naming,vault_ and indirect variables; and understand the template and conditional changes brought by data tagging starting in ansible-core 2.19.
Prerequisites: Lesson 1 Module 5’s variables and facts. Importance:★★★★★ (variable-override mistakes are one of the most common root causes of Ansible incidents)

What: variable precedence

Ansible collects variables from many places; when a same-named variable appears in several places, the final value is decided by the 22-level precedence defined in the official docs,higher levels override lower ones (scalars and lists are replaced directly; dictionaries are also replaced as a whole by default). The table below is ordered from low to high; bold marks the levels most commonly used day to day.

#SourceDescription / typical use
1Command-line options (such as -u my_user)These are not variables; they are connection parameters, with the lowest precedence
2role defaults (roles/x/defaults/main.yml)The role’s “factory defaults”,the easiest to override
3Group variables in an inventory file or scripthosts.ini in [group:vars] section
4inventory group_vars/allGlobal defaults (environment level)
5playbook group_vars/allgroup_vars/all in the directory next to the playbook
6inventory group_vars/*Per group (app, redis, prod, …)
7playbook group_vars/*
8Host variables in an inventory file or scripthosts.ini on the host line, ansible_host=… , etc.
9inventory host_vars/*Exceptions for a single host
10playbook host_vars/*
11Host facts / cached set_factansible_facts.* (injected ansible_* variables)
12play varsThe play’s vars:
13play vars_prompt
14play vars_files
15role vars (roles/x/vars/main.yml)Role-internal constants —override inventory!
16block varsOnly applies to tasks inside the block
17task varsOnly applies to that task
18include_varsVariable files loaded at runtime
19set_fact / registerValues computed at runtime
20role (and include_role) parametersParameters passed when calling a role
21include parametersinclude_tasks and other passed parameters
22extra vars (-e)Always wins, and cannot be overridden anywhere

Why: why you need to master it

Most “variable not taking effect” problems are precedence problems: you changed myapp_workers in group_vars, but the role author put it in vars/main.yml (level 15), so inventory can never override it; or someone in CI added -e, and everyone’s changes get swallowed. Understanding precedence lets you calculate the final value instead of trial and error.

How: rules and merge behavior between group variables

  • Parent and child groups: a child group overrides its parent group (all is the parent of all groups, so group_vars/app overrides group_vars/all).
  • Sibling groups: A host belongs to both app and canary , and when the two are sibling groups, variables are merged in alphabetical order of group name; the later one wins (canary first, app later → app wins). You can adjust this with the group variable ansible_group_priority (default 1; the higher number wins; can only be set in inventory sources).
  • Inventory directory vs playbook directory: Both locations’ group_vars/,host_vars/ are loaded, and for the same type the playbook directory takes precedence. This lesson consolidates everything under inventory/ , avoiding confusion from having both locations at once.
  • Dictionary replacement: By default hash_behaviour = replace, a higher-precedence dictionary replaces the lower-precedence one as a whole, rather than merging key by key. To merge, explicitly write {{ myapp_env_defaults | combine(myapp_env_overrides) }}. To change the global default to merge is not recommended (it makes every role’s behavior hard to predict).
  • Lazy evaluation: Templates inside variable values ("{{ myapp_home }}/venv") are rendered only when used, so you can reference variables defined later, or ones overridden at a higher level.
  • Types in extra vars:-e myapp_workers=4 Values in are strings "4"; for numbers, booleans, or lists, use JSON/YAML: -e '{"myapp_workers": 4}' or -e @overrides.yml.

Template and conditional changes starting with ansible-core 2.19 (data tagging)

2.19 rewrote the templating engine: every value carries a source “tag” (which file it came from, whether it is trusted, whether it is encrypted). This gives more accurate error messages, but also introduces several behavior changes (the official 2.19 porting guide is authoritative):

ChangeBeforeNow (2.19+, including 2.21)How to fix
Conditions must be booleanswhen: myapp_redis_password (a non-empty string is true)Error “Conditional result was '…' of type 'str' … Conditionals must have a boolean result.”when: myapp_redis_password | length > 0; temporarily you can set ALLOW_BROKEN_CONDITIONALS to downgrade it to a warning
Nested templates in expressionswhen: "{{ x }} == 1",failed_when: 1 + {{ value }} == 2Error “Template delimiters are not supported in expressions”; a template inside a template is no longer evaluated a second timeWrite the variable name directly: when: x == 1
Trusted templatesany {{ }} in any string may be rendered (including module return values)Only strings from the playbook, roles, vars files, and most built-in inventory plugins are treated as templates; untrusted strings are returned unchanged (silently, by default)Do not rely on tricks such as “rendering command output again as a template”
Native typesResult strings were “guessed” into Python literalsJinja native mode is the only mode; the final literal evaluation was removedConvert explicitly when a type is needed: | int,| bool,| from_json
Undefined valuesSome filters/tests silently accept undefined valuesUndefined values raise errors in filters and testsUse | default(...) or is defined
omit leakageomit inside a loop item affects task parametersNo longer leaksWrite {{ item.x | default(omit) }}

When: which layer variables go in (recommended organization conventions)

LayerWhat goes hereExample
role defaultsAll tunable parameters and their safe defaults (documented)myapp_port: 5000
role varsConstants tied to the OS or implementation that users should not changemyapp_packages,myapp_unit_file
group_vars/allEnvironment-level settings: timezone, NTP, monitoring addresses, domain namescommon_timezone
group_vars/<functional group>Parameters for that group’s servicesgroup_vars/app.yml: myapp_workers: 4
group_vars/<environment group>dev/prod differences (or one inventory directory per environment)inventories/prod/group_vars/…
host_varsTrue single-host exceptions (keep to a minimum)a large-memory machine’s myapp_workers: 8
extra varsOne-off runtime parameters: release version number, switches-e myapp_version=1.2.0

Naming conventions:① role variables always use the role name as a prefix (myapp_,redis_), and ansible-lint’s var-naming[no-role-prefix] rule checks this; ② secret variables start with vault_ , appear only in encrypted files, and are referenced by plain variables (myapp_redis_password: "{{ vault_myapp_redis_password }}", Module 4); ③ only lowercase letters, digits, and underscores are allowed, with no hyphens (my-var is not a valid variable name); ④ do not use name,port,environment,tags — names that match play keywords or magic variables.

Comparison with similar technologies

AnsibleTerraformHelm
Layers22 levels, by sourcedefault → tfvars → *.auto.tfvars → -var (later wins)chart values → -f files (later wins) → --set
Dictionary mergingReplaced by default (merge with combine)No merging (replaced as a whole)Deep merge
Highest precedenceextra vars (-e)-var / -var-file (command-line order)--set
Common misconceptions① “host_vars is the highest” — no; play vars, role vars, set_fact, and extra vars all rank above host_vars. ② “Dictionaries in group_vars/app.yml merge with dictionaries in defaults” — by default they do not; they are replaced as a whole, and other keys from the defaults dictionary “disappear” (switch to a dictionary variable in the animation to see this yourself). ③ “ansible-inventory --host node3 What is shown is the final value” — it only shows the inventory layers (levels 3–10) and cannot see role defaults/vars, play vars, or extra vars; to see the final value, use debug within a play.

Structure diagram: where variable sources sit in the project

inventory/ (levels 3–10) hosts.ini · inline group/host vars (3, 8) group_vars/all/main.yml (4) group_vars/all/vault.yml (4, encrypted) group_vars/app.yml (6) host_vars/node3.yml (9) Playbook and role roles/myapp/defaults/main.yml (2) site.yml play vars / vars_files (12, 14) roles/myapp/vars/main.yml (15) block / task vars (16, 17) role parameters · include parameters (20, 21) Runtime gather_facts → ansible_facts (11) include_vars (18) · set_fact/register (19) Command line -e / --extra-vars (22, highest) -u / -k and other connection options (1, not variables)
Figure 3-1 Physical locations of the variable sources and their precedence numbers (higher numbers take precedence)

Flowchart: how variables “stack up” within a play

defaults: workers=2 group_vars/all: 3 group_vars/app: 4 host_vars/node3: 6 -e workers=8 node3 final: 8 (with -e) / 6 (without -e)node2 is not in host_vars: 8 / 4 Dictionary variables: each layer is replaced as a whole unless combine is explicitly used
Figure 3-2 Layer-by-layer override from low to high: final value = the highest layer that defines the variable

Core animation: the variable precedence merge process

The same-named variable can be defined in all 8 layers. Check or uncheck each layer (simulating whether that file defines it), select a host and a variable, then play: Ansible starts from the lowest precedence and checks the definitions visible to this host layer by layer; later ones override earlier values. The dictionary variable demonstrates the default “replace as a whole” behavior.

Definitions at each layer (precedence increases from bottom to top)
Current value

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-inventory --host node3Variables for the host after merging at the inventory layers (levels 3–10)--yaml; --vars --graph View the group tree and variables
ansible-inventory --graph --varsGroup hierarchy + variables at each layerTroubleshoot parent/child group overrides
ansible node3 -m ansible.builtin.debug -a var=myapp_workersAd-hoc view (excludes role and play layers)Can only see inventory + extra vars
ansible.builtin.debug: var=… (within a play)View the final valueTasks placed inside a role or after one
-e key=value / -e '{"k": 4}' / -e @file.ymlextra varskey=value form values are strings
ansible-config dump | grep -iE "HASH|CONDITIONAL"View the hash_behaviour and ALLOW_BROKEN_CONDITIONALS settings--only-changed
ansible-inventory --host node3 --yaml
ansible-inventory --graph --vars | head -30
ansible_host: 172.30.0.13
common_timezone: America/Toronto
env: lab
motd_role: app
myapp_port: 5000
myapp_redis_host: '{{ hostvars[groups[''cache''][0]][''ansible_host''] }}'
myapp_workers: 6
ntp_server: pool.ntp.org
@all:
  |--@ungrouped:
  |--@lab:
  |  |--{env = lab}
  |  |--@lb:
  |  |  |--node1
  |  |  |  |--{ansible_host = 172.30.0.11}
  ...
  |  |--@app:
  |  |  |--node2
  |  |  |  |--{ansible_host = 172.30.0.12}
  |  |  |--node3
  |  |  |  |--{ansible_host = 172.30.0.13}
  |  |  |  |--{myapp_workers = 6}
  |  |  |--{myapp_workers = 4}
  ...

How to verify: Check the inventory layers with ansible-inventory; check the final value with debug inside a play. Common errors: Placing both a app.yaml file and a app/ directory in group_vars: both are loaded (all files in the directory load in alphabetical order), so duplicate definitions are easy to create. Production use: When reviewing variable changes, attach the before-and-after difference of ansible-inventory --host .

# View the final value and type of a variable in a play
- name: Show effective value
  ansible.builtin.debug:
    msg: "myapp_workers={{ myapp_workers }} (type: {{ myapp_workers | type_debug }})"
# Three ways to write extra vars
ansible-playbook site.yml -e myapp_workers=8                 # string "8"
ansible-playbook site.yml -e '{"myapp_workers": 8}'          # integer 8
ansible-playbook site.yml -e @overrides/hotfix.yml           # read from a file

Merging dictionaries (recommended syntax)

# roles/myapp/defaults/main.yml
myapp_env_defaults:
  LOG_LEVEL: info
  TZ: UTC
myapp_env_overrides: {}              # for users to override
myapp_env: "{{ myapp_env_defaults | combine(myapp_env_overrides) }}"

# inventory/group_vars/app.yml
myapp_env_overrides:
  LOG_LEVEL: warning                 # result: {LOG_LEVEL: warning, TZ: UTC}

Lab 3: define the same variable 5 times, then predict and verify the final value (about 6 minutes)

Create the group_vars / host_vars directory structure:
cd ~/ansible-lab
# Convert Lesson 1’s group_vars/all.yml into a directory (Module 4 will add vault.yml here)
mkdir -p inventory/group_vars/all
mv inventory/group_vars/all.yml inventory/group_vars/all/main.yml
cat >> inventory/group_vars/all/main.yml <<'EOF'
common_timezone: America/Toronto
myapp_workers: 3
EOF
sed -i 's/^myapp_workers: .*/myapp_workers: 4/' inventory/group_vars/app.yml
grep -n myapp_ inventory/group_vars/app.yml
cat > inventory/host_vars/node3.yml <<'EOF'
---
myapp_workers: 6        # node3 has larger specs
EOF

Now myapp_workers is defined in 4 places: role defaults (2), group_vars/all (3), group_vars/app (4), and host_vars/node3 (6).

Predict first, then verify: write a playbook that only displays the variable:
---
- name: Show effective variables
  hosts: app
  gather_facts: false
  roles:
    - role: myapp
      tags: [never]            # load only the role’s variables without running its tasks (the never tag is covered in Module 6)
  tasks:
    - name: Effective myapp_workers
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} myapp_workers={{ myapp_workers }} ({{ myapp_workers | type_debug }})"
ansible-playbook show-vars.yml
ansible-playbook show-vars.yml -e myapp_workers=8
ansible-playbook show-vars.yml -e '{"myapp_workers": 8}'
ok: [node3] => { "msg": "node3 myapp_workers=6 (int)" }
ok: [node2] => { "msg": "node2 myapp_workers=4 (int)" }
---- with -e myapp_workers=8 ----
ok: [node3] => { "msg": "node3 myapp_workers=8 (str)" }
ok: [node2] => { "msg": "node2 myapp_workers=8 (str)" }
---- with -e '{"myapp_workers": 8}' ----
ok: [node3] => { "msg": "node3 myapp_workers=8 (int)" }

type_debug Use your actual output for the displayed type names. Note that the key=value form yields str. In this example there is no difference once it is rendered into the unit file, but math or when: myapp_workers > 4 comparisons will error; argument_specs’ type: int will convert and validate it.

Demonstrate the role vars “trap”: temporarily add myapp_workers: 10 to roles/myapp/vars/main.yml:
echo "myapp_workers: 10" >> roles/myapp/vars/main.yml
ansible-playbook show-vars.yml
ansible-playbook show-vars.yml -e '{"myapp_workers": 8}'
sed -i '/^myapp_workers: 10$/d' roles/myapp/vars/main.yml     # restore
ok: [node3] => { "msg": "node3 myapp_workers=10 (int)" }
ok: [node2] => { "msg": "node2 myapp_workers=10 (int)" }
---- with -e ----
ok: [node3] => { "msg": "node3 myapp_workers=8 (int)" }

role vars (15) override all inventory layers; only extra vars can override them again. This is why “tunable parameters must go in defaults.”

set_fact overrides everything (except -e): add the following at the start of the tasks in show-vars.yml:
    - name: Compute workers from CPU count (2n+1)
      ansible.builtin.set_fact:
        myapp_workers: "{{ (ansible_facts.processor_vcpus | default(1) | int) * 2 + 1 }}"
      when: myapp_auto_workers | default(false) | bool
ansible-playbook show-vars.yml -e '{"myapp_auto_workers": true}'   # gather_facts must be changed to true

Expected: node3/node2 both become 2n+1 (n is the vCPU count seen by the container). Note that when use | bool to explicitly convert to a boolean — from 2.19 onward, this is a required good practice.

Experience 2.19’s strict conditionals:
cat > /tmp/cond.yml <<'EOF'
- hosts: localhost
  gather_facts: false
  vars: { pw: "s3cret" }
  tasks:
    - ansible.builtin.debug: { msg: "has password" }
      when: pw
EOF
ansible-playbook /tmp/cond.yml
fatal: [localhost]: FAILED! => {"msg": "Conditional result was 's3cret' of type 'str', which evaluates to True. Conditionals must have a boolean result."}

Change it to when: pw | length > 0 and it succeeds. Cleanup: rm /tmp/cond.yml. Keep show-vars.yml; it is used again later.

Case 1: after a production scale-out, the worker count did not change

Problem: Operations, in group_vars/prod.yml , changed app_workers from 4 to 8 and ran it; the service did not change. Approach: Debugging in the play showed the value was still 4; grep -rn app_workers found that the third-party role’s vars/main.yml hard-codes 4 (level 15). Configuration: Fork the role, move the variable into defaults, and declare it in argument_specs; also add a lint rule that checks tunable parameters in vars/. Limits: Modifying a third-party role means maintaining a branch; prefer submitting a PR upstream first.

Case 2: a dictionary “dropped keys” and the configuration went missing

Problem: The role defaults nginx_options has 12 keys, and one group only overrode client_max_body_size, so the other 11 keys all disappeared; nginx used its built-in defaults, and the timeout settings stopped working. Approach: Changed to the nginx_options_defaults + nginx_options_overrides + combine pattern (see the Commands page). Limits:combine(recursive=true) This covers nested dictionaries; lists are not merged, so use + or union.

Case 3: a “forgotten -e” in CI

Problem: To quickly fix something, the pipeline added -e myapp_version=1.4.2, and weeks later, upgrading versions in group_vars had no effect for anyone. Approach: Extra vars in the pipeline must come from parameterized input and be printed explicitly in the logs; regular configuration always goes into the inventory stored in Git. Limits: That extra vars cannot be overridden is by design; they can only be managed at the source.

Common errors and fixes

Changed group_vars, but debug still shows the old value

Cause: A higher layer defines a same-named variable (host_vars, play vars, role vars, set_fact, extra vars), or the file is not loaded (the file name does not match the group name, or it is in the wrong directory).

grep -rn "^myapp_workers" inventory/ roles/ *.yml
ansible-inventory --host node3 --yaml | grep myapp_workers
ansible-inventory --graph

Fix: Check from highest to lowest precedence: extra vars → set_fact → role vars → play vars → host_vars → group_vars. Confirm that the group file name matches the group name in inventory (app.yml corresponds to group app).

Conditional result was 'abc' of type 'str', which evaluates to True. Conditionals must have a boolean result.

Cause: ansible-core 2.19+ requires when/failed_when/changed_when/assert that to produce a boolean result.

Fix:| bool (for "yes"/"true" strings),| length > 0 (non-empty),is truthy,is defined. During the upgrade transition, you can set ALLOW_BROKEN_CONDITIONALS=True to downgrade the error to a warning, but fix it as soon as possible.

Syntax error in template: Template delimiters are not supported in expressions.

Cause: A {{ }} was nested inside a conditional expression, for example when: "{{ myapp_port }} == 5000".

Fix: The condition is already a Jinja2 expression, so write when: myapp_port == 5000 directly. Building expressions dynamically is no longer supported.

'dict object' has no attribute 'TZ' / some keys are missing from the rendered configuration

Cause: The dictionary was replaced as a whole by a higher-precedence layer.

ansible-playbook show-vars.yml -e '{"x":1}'   # in show-vars.yml, debug: var=myapp_env_extra

Fix: Use the defaults + overrides + combine pattern; avoid enabling hash_behaviour = merge globally.

[WARNING]: Found variable using reserved name: environment / Invalid variable name in 'vars' specified for 'play': 'my-var' is not a valid variable name

Cause: The variable name conflicts with a play keyword or magic variable, or contains a hyphen.

Fix: Change it to a valid prefixed name: myapp_environment,my_var.

Command-line practice questions
1. View all variables for node2 after merging at the inventory layers (YAML format).
ansible-inventory --host node2 --yaml
2. Pass an integer-typed extra var myapp_workers=8, and run it only against node3.
ansible-playbook site.yml --limit node3 -e '{"myapp_workers": 8}'
Scenario analysis
In the prod environment, myapp needs myapp_workers: 8, dev needs 2, and prod’s node7 needs 4 because its memory is small; in addition, an urgent release needs a temporarily specified version number. Please design a variable placement plan.

role defaults: myapp_workers: 2 (safe default); split by environment in inventory: inventories/prod/group_vars/app.yml: myapp_workers: 8,inventories/dev/ — leave it unset or set it to 2; inventories/prod/host_vars/node7.yml: myapp_workers: 4; the version number is passed by the pipeline as a one-off parameter -e myapp_version=…, or better, write it into group_vars and go through a PR (auditable). Do not put workers into role vars.

Verified teaching videos

▶
Ansible 101 - Episode 5 - Playbook handlers, environment vars, and variables — Jeff Geerling
2020 livestream series · English · explains variable sources, vars_files, include_vars, and precedence (recorded before core 2.19; for strict conditionals, data tagging, and so on, follow this lesson)

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: five transparent sheets stacked from bottom to top, each showing a different value of myapp_workers.
Narration: the same variable is written in five places; Ansible stacks them from lowest to highest, and the top one takes effect.
Shot 2 · 15–45s
Visual: the sheet labels in order are role defaults 2, group_vars all 3, group_vars app 4, host_vars node3 6, extra vars 8; from node2’s point of view, the host_vars sheet is missing.
Narration: role defaults is the lowest and extra vars the highest. Different hosts see different layers, so node3 and node2 get different results.
Shot 3 · 45–70s
Visual: a sheet labeled role vars 10 is inserted above host_vars, covering all inventory changes, with a red warning.
Narration: role vars override all inventory variables. Tunable parameters must always go in defaults.
Shot 4 · 70–90s
Visual: two dictionary sheets are stacked; the TZ key on the lower one disappears; with combine, both keys are kept.
Narration: dictionaries are replaced as a whole by default; when merging is needed, explicitly use the combine filter.
or score 70% or higher on the quiz

Module 4 · Ansible Vault and secrets

21:00 – 28:00 · Passwords can go into Git, but only in encrypted form; at runtime they are decrypted in memory and never appear in any log
7 minVault format 1.1 / 1.2 (AES256)core 2.19: EncryptedString★★★★★
Learning objectives
  • Use ansible-vault create / edit / view / encrypt / decrypt / rekey / encrypt_string, and distinguish when to encrypt an entire file versus a single value.
  • Understand the Vault encryption mechanism (PBKDF2-SHA256 key derivation → HMAC-SHA256 integrity check → AES-256-CTR), and use --vault-id label@source to manage multiple dev/prod passwords; the source can be a prompt, a file, or a client script.
  • Use vault_ indirect variables,no_log,diff: false to prevent secrets from leaking into output and logs; and explain the trade-offs between Ansible Vault and external secret management such as Azure Key Vault or HashiCorp Vault.
Prerequisites: Module 3’s variable organization. Importance:★★★★★

What: what Ansible Vault is

Ansible Vault is ansible-core’s built-in symmetric encryption: a single password (the vault password) encrypts YAML variable files, individual variable values, or even arbitrary files (certificates, private keys). The ciphertext is plain text and can be safely committed to Git; when running a playbook you provide the password, and Ansible decrypts in the control node’s memory, so modules receive plaintext parameters.

FormCommandCiphertext appearanceUse case
Encrypt an entire fileansible-vault encrypt vault.yml / create / editfirst line of the file $ANSIBLE_VAULT;1.1;AES256Secrets stored centrally in group_vars; files such as certificate private keys (the copy module decrypts them automatically src)
Encrypt a single valueansible-vault encrypt_stringkey: !vault | + multi-line ciphertextMix a few secrets into ordinary YAML; Git diffs remain readable

Why: why it is needed

  • Plaintext passwords in Git are a permanent leak (history cannot truly be deleted).
  • Secrets are versioned and reviewed together with the code that uses them, and you can start without any extra service.
  • Multi-environment: dev and prod use different vault passwords, so developers can work without the prod password.

How: the encryption mechanism and vault-id

  1. Header:$ANSIBLE_VAULT;1.1;AES256 (no label) or $ANSIBLE_VAULT;1.2;AES256;prod (format 1.2, with a vault-id label).
  2. Key derivation: random 32-byte salt + vault password → PBKDF2-HMAC-SHA256 (10000 iterations)→ derives the AES key, the HMAC key, and the counter’s initial value.
  3. Encryption and integrity: AES-256-CTR encrypts the plaintext; HMAC-SHA256 computes a message authentication code over the ciphertext. When decrypting,the HMAC is verified first, and a mismatch means “this password is wrong”, so the next candidate password is tried.
  4. Encoding: salt, HMAC, and ciphertext are each hex-encoded, joined with newlines, then hex-encoded again as a whole, and wrapped at 80 columns.
  5. vault-id:--vault-id label@source. The source can be prompt (interactive input), a password file path, or executable script (which prints the password to stdout; “client scripts” whose filenames end in -client or -client.extension also receive the --vault-id label argument, so one script can serve multiple labels). You can provide several --vault-id.
  6. Candidate order: By default, Ansible first tries the password whose label matches the ciphertext, then tries the other provided passwords in turn (the label is only a hint); after setting vault_id_match = True , only the label-matching password is tried.
  7. From 2.19: After decryption, the value is internally a string with an “encryption source” tag (EncryptedString replaces the old AnsibleVaultEncryptedUnicode), which is transparent to playbook authors; in custom plugins, checks for the old type isinstance need to be updated.

Leak prevention: Vault only protects secrets at rest

Leak pathProtection
Task result printing (-v stdout, failure messages, debug after register)no_log: true (the result displays as “the output has been hidden due to the fact that 'no_log: true' was specified for this result”)
--diff Showing file differences after template renderingOn the task, use diff: false (or no_log)
Items in loop outputloop_control: { label: "{{ item.key }}" }
Process list on the managed node (the command line contains the password)Pass it via environment variables or config files, for example REDISCLI_AUTH instead of redis-cli -a
callback plugins / log files / AWX job outputAlso depends on no_log; do not use ANSIBLE_DEBUG=1 in production runs.

When: Vault or external secret management

Ansible VaultExternal secret management (Azure Key Vault, HashiCorp Vault, AWS Secrets Manager, CyberArk)
Onboarding effortZero dependencies, built into ansible-coreRequires a service, network, and identity (managed identity / OIDC / AppRole)
RotationManual rekey and redeploy; rotating a value means editing and committing the fileServer-side rotation; the playbook looks up the latest value on each run
AuditingGit history (who changed the ciphertext); cannot audit “who read it”Every read has an audit log
Access control“Anyone with the vault password can read everything”Fine-grained policies by secret and by identity
Usage in Ansiblevault.yml in group_vars / !vaultlookup plugins: azure.azcollection.azure_keyvault_secret,community.hashi_vault.vault_kv2_get,amazon.aws.secretsmanager_secret (plugin names per each collection’s docs); external credential types in AAP
RecommendedSmall teams, labs, the bootstrapping phase; it can also be used only to store “credentials for accessing external secret services”Production, compliance requirements, multiple teams; demonstrated in Lesson 3 (Azure) and Lesson 4 (AWS)
Common misconceptions① “Once it is encrypted, it is secure” — the vault password itself is the root: the password file must be mode 600, must not go into Git, and is injected in CI via secret variables; after a departure or a leak, you must rekey and rotate the real protected passwords (old ciphertext remains in Git history). ② “no_log Using Vault makes variables automatically hidden in output” — it does not. Vault only handles encrypted storage; whether task output is printed is decided by no_log. ③ “ansible-vault encrypt_string Secrets can go in variable names” — variable names are plaintext and appear in Git, so do not put secrets in variable names (for example password_for_10.0.0.5 , which leaks the topology).

Architecture diagram: the path of secrets from Git to managed nodes

Git repository group_vars/all/vault.yml$ANSIBLE_VAULT;1.2;AES256;dev(ciphertext only) vault password source dev@~/.vault/dev.pass (600)prod@vault-pass-client.sh→ Key Vault / CI secret Control node (in memory) ① match the vault-id label ② PBKDF2-SHA256 × 10000 ③ verify HMAC-SHA256 ④ AES-256-CTR decrypt ⑤ render templates / module parameters no_log → output masked SSH channelAnsiballZ parameters(encrypted in transit) node1redis.confrequirepass (0640) Places that still need protection Terminal output / -v / AWX job logs → no_log--diff → diff: falseFile permissions / process arguments on managed nodes
Figure 4-1 Vault protects only the “storage” stage; transport relies on SSH, output on no_log, and files on disk on file permissions

Flowchart: structure of vault ciphertext

$ANSIBLE_VAULT;1.2;AES256;dev ← format version · algorithm · vault-id label (only in 1.2) hexlify( hexlify(salt) + "\n" + hexlify(HMAC-SHA256(ciphertext)) + "\n" + hexlify(AES-256-CTR(plaintext)) ) salt: randomly generated for each encryption (so the same plaintext encrypts differently every time, and the Git diff changes too) PBKDF2(password, salt, SHA256, 10000 iterations) → AES key 32B + HMAC key 32B + counter 16B Decrypt: compute and compare the HMAC first → mismatch = wrong password (try the next candidate) → decrypt only on match
Figure 4-2 Vault 1.1/1.2 format: random salt + authenticate after encryption (Encrypt-then-MAC)

Step-by-step animation: how Ansible decrypts a vault variable

Choose a scenario, then play. On the left is the list of candidate passwords when loading group_vars/all/vault.yml (label dev); on the right are the real processing steps and output.

Candidate passwords (in trial order)
Processing steps

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-vault create FILECreate a new encrypted file (opens $EDITOR)--vault-id dev@prompt
ansible-vault edit FILEDecrypts to a temp file for editing; re-encrypts on savePlaintext does not land in the working directory
ansible-vault view FILEView read-only
ansible-vault encrypt / decrypt FILE…Encrypt or decrypt an existing file in place--output - Outputs to stdout; --encrypt-vault-id dev When there are multiple ids, specify which one to encrypt with
ansible-vault encrypt_stringEncrypt a single value, output !vault YAML--name variable-name; --stdin-name variable-name Read from stdin (does not enter shell history)
ansible-vault rekey FILE…Change the vault password--new-vault-id dev@new.pass
ansible-playbook … --vault-id L@SRCProvide the password at runtimecan be repeated; --ask-vault-pass ≈ --vault-id @prompt; --vault-password-file
ansible.cfgDefault vault password sourcevault_identity_list,vault_encrypt_identity,vault_id_match,vault_password_file
mkdir -p ~/.vault && chmod 700 ~/.vault
openssl rand -base64 32 > ~/.vault/dev.pass && chmod 600 ~/.vault/dev.pass
# read the secret from stdin so it does not appear in shell history (after typing, press Ctrl+D twice, not Enter)
ansible-vault encrypt_string --vault-id dev@~/.vault/dev.pass --stdin-name vault_redis_password
Reading plaintext input from stdin. (ctrl-d to end input, twice if your content does not already have a newline)
vault_redis_password: !vault |
          $ANSIBLE_VAULT;1.2;AES256;dev
          62313365396662343061393464336163383764373764613633653634306231386433626436623361
          6437383330386363633431326163386565383931336532370a356138623664323530316332316433
          ...
Encryption successful

How to verify:ansible localhost -m ansible.builtin.debug -a var=vault_redis_password -e @inventory/group_vars/all/vault.yml --vault-id dev@~/.vault/dev.pass The plaintext can be displayed (only use this when verifying in a local terminal). Common errors: After typing, you pressed Enter, so an extra \n ended up at the end of the value and the password does not match — end input with Ctrl+D twice, or printf '%s' 'xxx' | ansible-vault encrypt_string --stdin-name .... Production use: In CI, use --vault-id prod@/run/secrets/vault-prod, where the password file is written into a temp directory from the pipeline’s secret store.

#!/usr/bin/env bash
# Ansible calls it as "vault-pass-client.sh --vault-id <label>"; the filename must end with -client or -client.<ext>
set -euo pipefail
label=""
while [ $# -gt 0 ]; do
  case "$1" in
    --vault-id) label="$2"; shift 2 ;;
    *) shift ;;
  esac
done
# read from Azure Key Vault (Lesson 3 configures a managed identity); can also be replaced with pass, secret-tool, or an environment variable injected by CI
az keyvault secret show --vault-name kv-ansible-lab --name "ansible-vault-${label}" --query value -o tsv
chmod 700 vault-pass-client.sh
ansible-playbook site.yml --vault-id dev@~/.vault/dev.pass --vault-id prod@./vault-pass-client.sh
[defaults]
vault_identity_list = dev@~/.vault/dev.pass
vault_encrypt_identity = dev        # the label used by encrypt / encrypt_string by default
# vault_id_match = True             # only try the label-matching password (clearer with multiple environments)

Lab 4: add a password to Redis and manage it with Vault (about 7 minutes)

Prepare the dev vault password and configure ansible.cfg (see the first two sections on the Commands page):
cd ~/ansible-lab
mkdir -p ~/.vault && chmod 700 ~/.vault
openssl rand -base64 32 > ~/.vault/dev.pass && chmod 600 ~/.vault/dev.pass
printf '\n# vault\n' >> ansible.cfg
# add in the [defaults] section: vault_identity_list = dev@~/.vault/dev.pass and vault_encrypt_identity = dev
grep -n "vault" ansible.cfg
Create the encrypted vault.yml (all secrets start with vault_ ):
REDIS_PW=$(openssl rand -hex 24)
cat > inventory/group_vars/all/vault.yml <<EOF
---
vault_redis_password: "${REDIS_PW}"
EOF
unset REDIS_PW
ansible-vault encrypt inventory/group_vars/all/vault.yml
head -2 inventory/group_vars/all/vault.yml
ansible-vault view inventory/group_vars/all/vault.yml
Encryption successful
$ANSIBLE_VAULT;1.2;AES256;dev
36623165613234393065643538663563353038623664653264383862346634383064633765313761
---
vault_redis_password: "9f2c…(48 hex digits)"
Plain variables reference vault variables (indirect reference: searching for redis_password in the plaintext file shows where it comes from):
redis_password: "{{ vault_redis_password }}"
myapp_redis_password: "{{ vault_redis_password }}"

Why put it in group_vars/all rather than the cache group? Because the app group’s hosts (myapp) also need the same password to connect to Redis.

Add no_log to tasks that contain secrets: myapp’s env template already sets diff: false; the configuration task in the redis role uses loop_control.label to print only the key names. Run:
ansible-playbook site.yml --diff
TASK [redis : Configure redis] *************************************************
changed: [node1] => (item=protected-mode)
changed: [node1] => (item=requirepass)
ok: [node1] => (item=maxmemory)
RUNNING HANDLER [redis : Restart redis] ****************************************
changed: [node1]
TASK [myapp : Render environment file] *****************************************
changed: [node3]
changed: [node2]
RUNNING HANDLER [myapp : Restart myapp] ****************************************
changed: [node3]
changed: [node2]

Note: with --diff , lineinfile still shows requirepass before/after differences! Add diff: false to the redis configuration task (or split requirepass into a separate task with no_log: true ). This is a clear illustration that “Vault only protects storage”.

Verify Redis now requires authentication, and myapp still works:
ansible node1 -b -m ansible.builtin.command -a "redis-cli ping"
ansible node1 -b -m ansible.builtin.shell -a "REDISCLI_AUTH='{{ vault_redis_password }}' redis-cli ping" --vault-id dev@~/.vault/dev.pass -o 2>/dev/null | sed 's/REDISCLI_AUTH=[^ ]*/REDISCLI_AUTH=***/'
curl -s http://172.30.0.11/ ; curl -s http://172.30.0.11/
node1 | CHANGED | rc=0 >>
NOAUTH Authentication required.
node1 | CHANGED | rc=0 | (stdout) PONG
Hello from node2, hits=14
Hello from node3, hits=15
(myapp connects to Redis successfully with the password; if it shows hits=N/A, app.py is not reading REDIS_PASSWORD)

When a vault variable is referenced in an ad-hoc command, Ansible will -v show the rendered command in the output. The sed masking here is only a demonstration; for production troubleshooting, write it as a task with no_log.

rekey: simulate rotation after a vault password leak:
openssl rand -base64 32 > ~/.vault/dev.pass.new && chmod 600 ~/.vault/dev.pass.new
ansible-vault rekey --vault-id dev@~/.vault/dev.pass --new-vault-id dev@~/.vault/dev.pass.new inventory/group_vars/all/vault.yml
mv ~/.vault/dev.pass.new ~/.vault/dev.pass
ansible-vault view inventory/group_vars/all/vault.yml | head -2
Rekey successful
---
vault_redis_password: "9f2c…"

rekey only replaced the “lock”,the protected Redis password itself did not change, and the old ciphertext still exists in Git history — in a real leak you must also generate a new Redis password (ansible-vault edit) and redeploy. Cleanup: none needed.

Case 1: dual dev / prod passwords; developers only hold dev

Problem: All environments share one vault password, so an intern can decrypt the production database password. Approach: One inventory directory per environment, with vault files encrypted separately using --encrypt-vault-id dev,prod ; ansible.cfg sets vault_id_match = True; the prod password exists only in the CI secret store and in the release owner’s password manager. Limits: Developers cannot run --check against the prod inventory locally; a sanitized staging environment can be offered.

Case 2: the Vault password comes from Azure Key Vault

Problem: Vault password files are scattered across several jump hosts, which makes rotation difficult. Approach: Use the client script vault-pass-client.sh, so jump hosts and self-hosted runners use a managed identity to read the ansible-vault-prod from Key Vault; rotation only requires updating the value in Key Vault and rekeying. Limits: The script depends on the az CLI and the network; the EE needs az installed (Module 8), or you switch to an external credential plugin in AAP.

Case 3: migrating from Vault to external secret management

Problem: Audit requires that “every read is recorded”, and the database password must be rotated automatically every 30 days. Approach: Change the definition of vault_db_password from vault.yml to a lookup: db_password: "{{ lookup('community.hashi_vault.vault_kv2_get', 'myapp/db', engine_mount_point='kv').secret.password }}" (parameters per the collection docs); the caller’s variable name stays the same and the role needs no changes — this is the value of indirect variables. Limits: The lookup runs on the control node and is called on every reference for every host (you can cache it once with set_fact).

Common errors and fixes

ERROR! Attempting to decrypt but no vault secrets found

Cause: The playbook loaded an encrypted file or variable, but no vault password was provided (there is no --vault-id, and ansible.cfg has no vault_identity_list).

ansible-config dump --only-changed | grep -i vault
grep -rl '\$ANSIBLE_VAULT' inventory/ roles/

Fix: Add --vault-id dev@~/.vault/dev.pass, or configure vault_identity_list in ansible.cfg.

ERROR! Decryption failed (no vault secrets were found that could decrypt) on inventory/group_vars/all/vault.yml

Cause: A password was provided, but all HMAC checks failed: wrong password; the password file has an extra or missing trailing newline (in most cases Ansible strips a trailing newline, but other whitespace from script output is not stripped); or the label did not match when using vault_id_match=True with a mismatched label, or the file has been rekeyed.

head -1 inventory/group_vars/all/vault.yml        # check the label
ansible-vault view --vault-id dev@~/.vault/dev.pass inventory/group_vars/all/vault.yml >/dev/null && echo OK

Fix: Confirm you used the correct environment’s password; when labels do not match, provide the password with the matching label; re-obtain it from the password manager.

fatal: [node1]: FAILED! => {"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result"}

Cause: A task with no_log failed and its error details are hidden — this is expected behavior, but it makes troubleshooting difficult.

Fix: In an isolated test environment, temporarily set no_log: "{{ not (debug_secrets | default(false) | bool) }}" and run it with -e '{"debug_secrets": true}' ; do not enable it in production or CI logs.

WARNING: Error in vault password file loading (dev): Problem running vault password script … ([Errno 13] Permission denied)

Cause: The source was executed as a script (the file has the executable bit), but execution failed; or a regular password file was made executable.

Fix: A regular password file chmod 600 (it should not have the x bit); the script chmod 700 must run standalone and only output the password to stdout. Client script names must end in -client to receive the --vault-id argument.

git diff of vault.yml changes entirely every time / merge conflicts cannot be resolved

Cause: Each encryption uses a random salt,ansible-vault edit so the whole ciphertext changes.

Fix: When there are few secrets, use encrypt_string, so changes only affect a single value; configure Git’s textconv: .gitattributes in *vault.yml diff=ansible-vault,git config diff.ansible-vault.textconv "ansible-vault view", and local diffs will show plaintext differences (note that this displays secrets in the terminal).

Command-line practice questions
1. Using the prod label and interactive password input, encrypt the variable vault_db_password, reading the value from stdin.
ansible-vault encrypt_string --vault-id prod@prompt --stdin-name vault_db_password
2. Run site.yml while providing both the dev (file) and prod (client script) vault passwords.
ansible-playbook site.yml --vault-id dev@~/.vault/dev.pass --vault-id prod@./vault-pass-client.sh
Scenario analysis
An engineer with the dev vault password leaves the company. They also briefly obtained the prod vault password at one point. What do you need to do?

① run rekey on all dev and prod vault files (distribute the new password only to current staff and CI); ② because old ciphertext is still in Git history and they may already have decrypted it,rotate all protected real credentials (database, Redis, API tokens), using ansible-vault edit to write new values and deploy; ③ check the password files and permissions on CI and jump hosts; ④ in the long term, consider migrating to external secret management with auditing and automatic rotation, or have the vault password itself issued by a service such as Key Vault based on identity.

Verified teaching videos

▶
Ansible 101 - Episode 6 - Ansible Vault and Roles — Jeff Geerling
2020 livestream series · English · the first half explains ansible-vault encryption, editing, and providing passwords at runtime (for multi-password vault-id and the 2.19 internal type changes, follow this lesson)

Official docs

Video storyboard (about 80 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–15s
Visual: plaintext password text appears in a Git commit history, with a red alert.
Narration: once a plaintext password enters Git, it stays in the history forever.
Shot 2 · 15–40s
Visual: the encrypt_string command outputs multi-line ciphertext with the $ANSIBLE_VAULT header; the dev label is highlighted.
Narration: Ansible Vault encrypts variables with one password. The header of format 1.2 carries a vault-id label, used to tell dev from prod.
Shot 3 · 40–65s
Visual: the password and salt enter a PBKDF2 funnel, producing three keys; the HMAC is compared first, and after a green check mark, AES decrypts.
Narration: when decrypting, the HMAC is verified first; if verification fails, the password is wrong; on success, decryption happens in control-node memory.
Shot 4 · 65–80s
Visual: in task output, the password is replaced with a hidden notice; diff: false keeps the file differences from showing.
Narration: Vault only protects storage; output still relies on no_log and diff: false.
or score 70% or higher on the quiz

Module 5 · Error handling: block, rescue, failed_when

28:00 – 35:00 · Make “failure” predictable: fail when it should, roll back when it can, and stop all hosts together when they should stop
7 minansible-core 2.212.19+: conditions must be boolean★★★★★
Learning objectives
  • Default failure semantics: when a task fails on a host, that host is removed from the rest of this play while other hosts continue; understand the meaning of ok / changed / failed / rescued / ignored in PLAY RECAP.
  • Be able to use block / rescue / always to implement “automatic rollback on deployment failure”, using ansible_failed_task,ansible_failed_result in rescue.
  • Be able to use failed_when,changed_when to correct module judgments of “success / changed”; know the limits of ignore_errors ; and use any_errors_fatal,serial + max_fail_percentage to control the “blast radius” of failures.
Prerequisites: Module 1’s roles, and Lesson 1’s register and handlers. Importance:★★★★★

What: how Ansible handles failure by default

Each task returns JSON on each host; failed: true (or a module exception, or a command with a non-zero return code) counts as a failure. By default (linear strategy): failed hosts are removed from the subsequent tasks of the current play, while other hosts continue; at the end of the play, RECAP shows failed=1,ansible-playbook the exit code is non-zero (2 means some host failed, 4 means some host is unreachable). Queued handlers by default do not run on failed hosts (unless force_handlers: true or --force-handlers).

KeywordPurposeNotes
blockGroups multiple tasks together, sharing attributes such as when / become / tags / varsblock itself is not a loop and cannot loop
rescueRuns when any task in the block fails (like catch)After rescue completes successfully, the host is no longer treated as failed (rescued=1 in RECAP); you can use ansible_failed_task,ansible_failed_result
alwaysRuns whether the tasks succeed or fail (like finally)Suitable for cleaning up temp files, writing audit records, sending notifications
ignore_errors: trueContinue running subsequent tasks after a task failscounted as ignored in RECAP; cannot ignore unreachable (use ignore_unreachable), undefined variables, or syntax errors
failed_whenCustom failure conditionsA list means “fail only if all are true” (AND); failed_when: false never fails
changed_whenCustom “whether changed”For read-only commands, write changed_when: false, otherwise it breaks idempotence reporting (lint and Molecule in Module 7 both catch this)
any_errors_fatal: trueIf any host fails, all hosts stop the play after the current task finishesSuitable for changes where “the cluster must be consistent” (database primary/replica, config distribution)
serial + max_fail_percentageRuns in batches; stops subsequent batches once the failure ratio is exceededThe core of rolling releases; also stops if an entire batch fails
until / retries / delayRetry until the condition is metHealth checks, waiting for ports; counts as a failure only after retries are exhausted

Why: why the default behavior is not enough

  • When a deployment fails halfway, hosts are left in an intermediate state of “new code + old config” or “service stopped”; the default behavior will not help you recover.
  • Many command return codes are unreliable: grep not found returns 1 (not necessarily an error), and some scripts still return 0 when they fail.
  • command/shell Always reporting changed hides real changes and makes the Molecule idempotence test fail.
  • In cluster changes, “one host fails, others continue” can cause split brain or inconsistent configuration.

How: execution order and semantics

  1. Tasks in a block run in order on each host; if a host fails at task k, that host skips the remaining tasks in the block and enters rescue.
  2. If all tasks in rescue succeed, the host’s failure state is cleared (subsequent tasks after the block continue); if rescue fails again (including when you ansible.builtin.fail explicitly “re-raise”), the host fails.
  3. always always runs after block/rescue (even if rescue fails).
  4. failed_when/changed_when Evaluated on the control node after the module returns; can reference register results; ansible-core 2.19+ requires the result to be a boolean.
  5. any_errors_fatal Set at play or block level: after the current task has run on all hosts, if any host failed, all hosts terminate the play (if the block has a rescue, rescue is entered first).

When: which mechanism to choose

ScenarioRecommended
Release failure needs rollbackblock (release + health check) / rescue (rollback + fail to re-raise) / always (record)
Command return code does not represent success or failureregister + failed_when
Read-only query commandschanged_when: false (can add check_mode: false, so it also runs in --check)
“Try it; failure doesn’t matter”Prefer failed_when with an exact expression; use the other only when failure truly does not matter. ignore_errors
Multiple nodes must be consistentany_errors_fatal: true
Rolling releases to control the blast radiusserial: [1, "30%"] + max_fail_percentage: 0

Comparison with similar technologies

AnsibleBashTerraform
try/catchblock / rescue / alwaysset -e + trapNone (after a failure, state is partially written; fix it on the next plan)
Custom failurefailed_when|| exit 1precondition / postcondition
Parallel failure controlany_errors_fatal, serial, max_fail_percentageManual-parallelism, no concept of batches
Common misconceptions① “After rescue, the playbook succeeded” — a successful rescue clears the failure state; if you want CI to know that a rollback happened, you must use ansible.builtin.fail to fail again at the end of rescue. ② “ignore_errors can ignore everything” — no; it cannot ignore unreachable hosts, undefined variables in templates, or syntax errors. ③ “failed_when: result.rc != 0 or 'ERROR' in result.stdout is always safe” — if the module fails before it runs (for example, the command does not exist), the registered variable result.stdout may be undefined; since 2.19, filters and tests raise errors on undefined values, so write result.stdout | default('') with a default.

Flowchart: control flow of block / rescue / always

block: release 1.1.0 ① create releases/1.1.0 and copy the code ② switch the current symlink ③ restart myapp ④ /healthz retried 10 times → fails rescue: rollback ansible_failed_task.name = ④ symlink points back to 1.0.0 restart myapp set_fact status=ROLLED_BACK fail: re-raise (turns CI red) always write the deployment record/var/log/myapp-deploy.log(runs whether it succeeds or fails) any task fails all succeed: skip rescue, go straight to always
Figure 5-1 A release is a transaction: block does the work, rescue rolls back, always keeps the books

Flowchart: comparison of multi-host failure strategies

Default node3 continues node2 fails → removed node1 continues any_errors_fatal node3 stops node2 fails node1 stops serial: 1 Batch 1 node3 ✓ Batch 2 node2 ✗ Batch 3 not run ignore_errors node3 continues node2 ignored, continues node1 continues Default: a failure only affects itself any_errors_fatal: one fails, all stop serial: in batches; no further batches after a bad batch max_fail_percentage: failure ratio threshold within a batch ignore_errors: recorded as ignored, execution continues block+rescue: failed hosts take the rollback branch
Figure 5-2 Several ways to control the “blast radius” of failures

Interactive simulator: multi-host failure handling

One play runs 4 tasks on 3 hosts (illustrative; think of it as the app group after scale-out); tasks 2–4 are inside a block. Choose which host fails at which task, turn each mechanism on or off, then play, and observe each host’s state and the final PLAY RECAP.

Core syntax and parameters

SyntaxPurposeNotes
block / rescue / alwaysTransactional task groupNestable; block-level when applies to each task inside
ansible_failed_task / ansible_failed_resultget the failed task and its results in rescueansible_failed_task.name,ansible_failed_result.msg
failed_when: …Custom failurelist = AND; for OR, write it in one expression
changed_when: …Custom changeuse for read-only commands false
until / retries / delayRetrydefault retries 3, delay 5 (per the docs)
any_errors_fatal / max_fail_percentage / serialPlay-level failure strategySee the principles table
--force-handlersFailed hosts still run notified handlersor play-level force_handlers: true
--start-at-task "NAME" / --stepStart from a certain task / confirm each task one by oneAfter fixing, continue; note that variables registered by skipped tasks do not exist
# Typical usage of failed_when / changed_when
- name: Check redis responds (read-only)
  ansible.builtin.command: redis-cli ping
  environment:
    REDISCLI_AUTH: "{{ redis_password }}"
  register: redis_ping
  changed_when: false
  failed_when: "'PONG' not in (redis_ping.stdout | default(''))"
  no_log: true

- name: Run DB migration script (prints "MIGRATED n" or "NOTHING TO DO")
  ansible.builtin.command: "{{ myapp_home }}/current/migrate.sh"
  register: myapp_migrate
  changed_when: "'MIGRATED' in myapp_migrate.stdout"
  failed_when: myapp_migrate.rc != 0 or 'ERROR' in myapp_migrate.stdout

- name: grep returns 1 when nothing matched — not an error
  ansible.builtin.command: grep -c ERROR /var/log/myapp.log
  register: myapp_errors
  changed_when: false
  failed_when: myapp_errors.rc not in [0, 1]

How to verify: Read-only tasks no longer count toward changed in RECAP; failed_when when you write it wrong, you can use -vvv to see the full structure of register. Common errors: Writing multiple conditions as a list and thinking it is OR (it is actually AND). Production use: Have your own scripts output an explicit “what was done” marker (such as MIGRATED n), so Ansible can report changed accurately; for operations a module can do (such as cleaning up old versions with ansible.builtin.find + ansible.builtin.file), prefer the module, since modules are naturally idempotent and support check mode.

# Rolling release + stop on failure
- name: myapp rolling deploy
  hosts: app
  become: true
  serial: 1
  max_fail_percentage: 0
  roles:
    - role: myapp

Lab 5: automatic rollback on release failure (about 7 minutes)

Change to a release method of “version directory + current symlink”: create roles/myapp/tasks/release.yml, and in install.yml delete the “Deploy application code” task:
---
- name: Find current release
  ansible.builtin.stat:
    path: "{{ myapp_home }}/current"
  register: myapp_current

- name: Deploy release {{ myapp_version }}
  block:
    - name: Create release directory
      ansible.builtin.file:
        path: "{{ myapp_home }}/releases/{{ myapp_version }}"
        state: directory
        owner: "{{ myapp_user }}"
        group: "{{ myapp_user }}"
        mode: "0755"

    - name: Copy application code
      ansible.builtin.copy:
        src: "{{ myapp_app_source }}"
        dest: "{{ myapp_home }}/releases/{{ myapp_version }}/app.py"
        owner: "{{ myapp_user }}"
        group: "{{ myapp_user }}"
        mode: "0644"

    - name: Switch current symlink
      ansible.builtin.file:
        src: "{{ myapp_home }}/releases/{{ myapp_version }}"
        dest: "{{ myapp_home }}/current"
        state: link
        force: true
      register: myapp_link

    - name: Restart myapp when release changed
      ansible.builtin.systemd_service:
        name: myapp
        state: restarted
        daemon_reload: true
      when: myapp_link is changed

    - name: Wait for health check
      ansible.builtin.uri:
        url: "http://127.0.0.1:{{ myapp_port }}{{ myapp_healthcheck_path }}"
        status_code: 200
      register: myapp_health
      retries: 10
      delay: 2
      until: myapp_health.status == 200

  rescue:
    - name: Roll back current symlink
      ansible.builtin.file:
        src: "{{ myapp_current.stat.lnk_source }}"
        dest: "{{ myapp_home }}/current"
        state: link
        force: true
      when: myapp_current.stat.islnk | default(false)

    - name: Restart previous release
      ansible.builtin.systemd_service:
        name: myapp
        state: restarted

    - name: Mark deployment as rolled back
      ansible.builtin.set_fact:
        myapp_deploy_status: ROLLED_BACK

    - name: Fail after rollback so that CI notices
      ansible.builtin.fail:
        msg: >-
          Release {{ myapp_version }} failed at '{{ ansible_failed_task.name }}';
          rolled back to {{ (myapp_current.stat.lnk_source | default('none')) | basename }}

  always:
    - name: Record deployment attempt
      ansible.builtin.lineinfile:
        path: /var/log/myapp-deploy.log
        line: "{{ now(utc=true).isoformat() }} {{ myapp_version }} {{ myapp_deploy_status | default('OK') }}"
        create: true
        owner: root
        group: root
        mode: "0644"
- name: Release
  ansible.builtin.import_tasks: release.yml
  tags: [release]
# add one line to defaults; change the unit template to run from the current directory
echo 'myapp_app_source: app.py' >> roles/myapp/defaults/main.yml
sed -i 's#^WorkingDirectory=.*#WorkingDirectory={{ myapp_home }}/current#' roles/myapp/templates/myapp.service.j2
grep WorkingDirectory roles/myapp/templates/myapp.service.j2

The deployment record in always is appended on every run, so this task reports changed every time — a deliberate trade-off between “audit records” and “idempotence”; in Module 7’s Molecule idempotence test, use the molecule-idempotence-notest tag to exclude it.

Normal release of 1.0.0 and 1.1.0:
ansible-playbook site.yml --limit app -e myapp_version=1.0.0
ansible-playbook site.yml --limit app -e myapp_version=1.1.0
ansible app -b -m ansible.builtin.command -a "readlink /opt/myapp/current"
node3 | CHANGED | rc=0 >>
/opt/myapp/releases/1.1.0
node2 | CHANGED | rc=0 >>
/opt/myapp/releases/1.1.0
Create a bad version and release it (the application exits on startup):
printf 'raise SystemExit("boom: bad release")\n' > roles/myapp/files/app_broken.py
ansible-playbook site.yml --limit app -e myapp_version=1.2.0-bad -e myapp_app_source=app_broken.py
TASK [myapp : Wait for health check] *******************************************
FAILED - RETRYING: [node3]: Wait for health check (10 retries left).
...
fatal: [node3]: FAILED! => {"attempts": 10, "changed": false, "msg": "Status code was -1 and not [200]: Request failed: <urlopen error [Errno 111] Connection refused>", ...}
TASK [myapp : Roll back current symlink] ***************************************
changed: [node3]
TASK [myapp : Restart previous release] ****************************************
changed: [node3]
TASK [myapp : Fail after rollback so that CI notices] **************************
fatal: [node3]: FAILED! => {"changed": false, "msg": "Release 1.2.0-bad failed at 'Wait for health check'; rolled back to 1.1.0"}
TASK [myapp : Record deployment attempt] ***************************************
changed: [node3]
PLAY RECAP *********************************************************************
node3  : ok=14  changed=6  unreachable=0  failed=1  skipped=0  rescued=1  ignored=0
node2  : ok=14  changed=6  unreachable=0  failed=1  skipped=0  rescued=1  ignored=0
Verify it has rolled back and the service is healthy:
ansible app -b -m ansible.builtin.command -a "readlink /opt/myapp/current"
ansible app -b -m ansible.builtin.command -a "tail -3 /var/log/myapp-deploy.log"
curl -s -o /dev/null -w '%{http_code}' http://172.30.0.11/; echo
node3 | CHANGED | rc=0 >>
/opt/myapp/releases/1.1.0
node3 | CHANGED | rc=0 >>
2026-11-15T10:02:11.418233+00:00 1.0.0 OK
2026-11-15T10:03:40.902114+00:00 1.1.0 OK
2026-11-15T10:05:22.117604+00:00 1.2.0-bad ROLLED_BACK
200
Add serial to shrink the blast radius to one host: add serial: 1 and max_fail_percentage: 0 to the myapp play in site.yml, then release the bad version again:
ansible-playbook site.yml --limit app -e myapp_version=1.2.0-bad -e myapp_app_source=app_broken.py
PLAY [myapp (app tier)] ******** (batch 1: node2, in the order of [app] in inventory)
...
fatal: [node2]: FAILED! => {"msg": "Release 1.2.0-bad failed at 'Wait for health check'; rolled back to 1.1.0"}
NO MORE HOSTS LEFT *************************************************************
PLAY RECAP *********************************************************************
node2  : ok=14  changed=5  unreachable=0  failed=1  skipped=0  rescued=1  ignored=0

node3 was not touched at all (it does not appear in RECAP), and nginx keeps sending traffic to node3 and the rolled-back node2. Cleanup: rm roles/myapp/files/app_broken.py, then use -e myapp_version=1.1.0 to confirm everything is fine.

Case 1: a database migration failure leaves the system half-upgraded

Problem: The release process is “stop service → migrate → deploy → start”; after the migration fails, the service stays stopped until someone notices manually. Approach: Put the migration and deployment in a block; in rescue, restore the old version and start the service; send notifications in always. The migration itself must be backward compatible (expand/contract) so the application can be rolled back safely. Limits: Ansible’s rescue cannot roll back database changes that have already run — data-layer rollback depends on the migration tool and backups.

Case 2: Kafka/ZooKeeper cluster configuration inconsistency

Problem: While changing cluster membership configuration, one node failed because its disk was full, while the other nodes continued restarting, so the cluster ended up with two membership views. Approach: Set at play level any_errors_fatal: true, run pre-checks (disk, version) on all nodes first and change the configuration only after all pass; restart with serial: 1 and check cluster health after each host. Limits: any_errors_fatal only stops subsequent tasks; the current task that already ran on other hosts is not undone.

Case 3: a “green” playbook hides failures

Problem: A script task returned 0 when it failed, so Ansible showed changed, and the problem only surfaced the next day. Another task had ignore_errors: yes, which hid the fact that the apt source was unavailable. Approach: Add failed_when to script output (check keywords or result files); clean up all ignore_errors, and replace them with precise failed_when; ansible-lint’s ignore-errors rule flags them. Limits: failed_when depends on the output format, so keep it in sync when the script is upgraded.

Common errors and fixes

The conditional check 'result.stdout.find("OK") != -1' failed. The error was: error while evaluating conditional … 'dict object' has no attribute 'stdout'

Cause: The module failed or was skipped, so the registered result has no stdout (for example, the command does not exist, or command was skipped in check mode).

ansible-playbook site.yml -vvv --limit node3 2>&1 | grep -A20 "TASK \[myapp : Check"

Fix:failed_when: "'OK' not in (result.stdout | default(''))"; for check mode, add check_mode: false (for read-only commands).

ERROR! 'rescue' is not a valid attribute for a Task

Cause: The indentation of rescue/always does not line up with block, or they were written on a single task.

Fix:block:,rescue:,always: The three must be sibling keys of the same block task.

rescue ran, but PLAY RECAP shows failed=0, so CI thinks the deployment succeeded

Cause: A successful rescue clears the failure state (rescued=1).

Fix: At the end of rescue, use ansible.builtin.fail to re-raise the failure; CI then judges by the exit code.

FAILED - RETRYING … (0 retries left) followed by Status code was -1 and not [200]: Request failed: <urlopen error [Errno 111] Connection refused>

Cause: The service did not come up within the retry window: the application crashed, the port is wrong, or startup is slow.

ansible node3 -b -m ansible.builtin.command -a "journalctl -u myapp -n 30 --no-pager"
ansible node3 -b -m ansible.builtin.command -a "systemctl status myapp --no-pager"

Fix: Check the Python exception in the journal; increase retries × delay; confirm myapp_port matches the bind in the unit.

[WARNING]: … ignore_errors does not apply to unreachable hosts / fatal: [node2]: UNREACHABLE!

Cause: A connection failure is not a task failure, and the semantics of ignore_errors and rescue do not cover it.

Fix: In scenarios where it is truly acceptable, use ignore_unreachable: true; otherwise troubleshoot SSH (the Lesson 1 troubleshooting tree); use max_fail_percentage to tolerate a few unreachable hosts.

Command-line practice questions
1. Write a task that runs systemctl is-active myapp, which is read-only, does not report changed, and fails when the state is not active.
- name: myapp must be active
  ansible.builtin.command: systemctl is-active myapp
  register: myapp_active
  changed_when: false
  failed_when: myapp_active.stdout | default('') != 'active'
2. After fixing the problem, re-run starting from the task “Wait for health check”, only for node3.
ansible-playbook site.yml --limit node3 --start-at-task "Wait for health check"

Note: the skipped “Find current release” task will not run, so the variables referenced in rescue myapp_current will not exist — this is the risk of start-at-task.

Scenario analysis
You need to push a new TLS certificate to 20 web servers and reload nginx. Requirements: if any server fails certificate validation, stop everything; reloads proceed in batches of 25%, and if any batch fails, stop the subsequent batches. How would you write this?

First play: hosts: web,any_errors_fatal: true, with tasks that copy the certificate to a temp path + openssl x509 -checkend/community.crypto.x509_certificate_info validation (changed_when: false). Second play: serial: "25%",max_fail_percentage: 0, the block moves the certificate to its final location, plus nginx -t + reload + health check; rescue restores the old certificate and reloads, then fails.

Instructional videos

No verified video specifically covering block/rescue/always and failed_when was found. As background, you may refer to Jeff Geerling’s “Ansible 101” series, “Ansible 101 - Episode 4 - Your first real-world playbook” (SLW4LX7lbvE, title and channel already verified via oEmbed) as background; the content of this module follows the official docs.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: three servers release a new version; the middle one shows a red cross, while the other two keep turning green.
Narration: by default, when one host fails, only that host is removed from the play; the other hosts continue.
Shot 2 · 20–50s
Visual: a block box with four steps; at step four the health check fails, and an arrow jumps to the rescue box: the symlink points back to the old version, restart, fail; finally it enters always to write the log.
Narration: block does the work, rescue rolls back, always keeps the books. Rescue fails once more at the end, so the pipeline knows a rollback happened.
Shot 3 · 50–75s
Visual: the command task shows a yellow changed each time; after adding changed_when: false it turns green; grep returning 1 is judged normal by failed_when.
Narration: changed_when and failed_when correct the module judgments so the results can be trusted.
Shot 4 · 75–90s
Visual: serial: 1; after the first batch fails, the servers behind it stay grey and unexecuted.
Narration: rolling releases combined with a failure ratio limit the impact of a bad release to one machine.
or score 70% or higher on the quiz

Module 6 · Tags, check, and diff modes

35:00 – 41:00 · Run only the part you need, and see clearly “what will change” before acting
6 minansible-core 2.21★★★★☆
Learning objectives
  • Be able to use --tags / --skip-tags / --list-tags, understand the special tags always,never and tagged,untagged,all.
  • Explain the tag inheritance rules: tags on play / role / block / import_* are passed to all child tasks; tags on include_* only apply to the include statement itself (to make the inner tasks carry them, you need apply).
  • Be able to use --check --diff to rehearse changes, know which modules do not support check mode (they get skipped), and how to use check_mode,ansible_check_mode so the playbook also runs through in check mode.
Prerequisites: Module 1’s import / include. Importance:★★★★☆ (the foundation of production change review)

What: what tags, check, and diff each are

FeatureCommand linePurpose
Tags--tags config,--skip-tags installselect tasks to run or skip by tag
Check mode (dry run)--check / -CModules that support check only predict whether they would change, without modifying the target; unsupported modules are skipped
Diff mode--diff / -DModules that support diff (template, copy, lineinfile, file, etc.) show before/after differences; can be combined with check

Special tags

TagBehavior
alwaysAlways runs regardless of --tags what is selected, unless --skip-tags always. gather_facts and the role argument validation task carry this tag by default
neverNot run by default; it runs only when --tags explicitly names one of its tags (or never) — suitable for dangerous operations and debug tasks
--tags tagged / untagged / allRun tagged / untagged / all (the default is all, but it excludes never)

Why: why it is needed

  • A full site.yml may take 10 minutes to run; when only the nginx configuration changed,--tags config finishes in one minute, with a smaller change surface.
  • Change review: --check --diff output can be pasted into the change ticket, so approvers can see the exact lines that will change.
  • Drift detection: running in check mode on a schedule; changed > 0 indicates someone manually changed the server.

How: implementation of tag inheritance and check mode

  • Inheritance: Tags can be set on play, role (roles: [{role: myapp, tags: [app]}]), block, task,import_* ,— they accumulate downward to all child tasks. include_* is expanded at runtime; Ansible does not know the tasks inside at parse time, so tags on an include only decide whether the include itself runs; to make the inner tasks carry the tags, use apply: { tags: [...] }, or tag each inner task individually.
  • Selection logic: The effective tag set of a task and --tags intersect (or it contains always) → selected; then, if it intersects --skip-tags , it is skipped. --list-tasks --tags X It can be previewed.
  • check mode: The control node passes _ansible_check_mode=True along with the module parameters to the remote side; the module decides for itself and returns changed predictions; in the module doc’s Attributes table, check_mode is full / partial / none. For example, ansible.builtin.uri is none (skipped in check mode), and ansible.builtin.command is partial (it only predicts when used with creates/removes ; otherwise it is skipped).
  • Task-level control:check_mode: false → runs for real even under --check (read-only commands); check_mode: true → always runs in check mode. The variable ansible_check_mode indicates whether check mode is currently active.
  • diff: The module returns diff fields (before/after), and the callback handles display; at the task level, diff: false turns it off (for templates containing secrets).

When: best practices

  • Tag by stage (install / config / release / service) rather than by task name; keep it under ten tags and document them in the README; the myapp role in this lesson is already organized this way.
  • For dangerous or slow tasks (data rebuilds, full backups), add never plus a specific tag.
  • Use --check --diff as a PR preview step in CI; run scheduled check mode as drift detection.
  • When writing a role, design for check compatibility from the start: tasks that depend on earlier changes get when: not ansible_check_mode, and read-only commands get check_mode: false + changed_when: false.

Comparison with similar technologies

Ansible --check --diffterraform plankubectl diff / --dry-run=server
AccuracyDepends on each module’s implementation; dependency chains can “break”Provider-based plan, more completeValidated on the API server side, more complete
When unsupportedTask is skipped (may hide subsequent changes)(known after apply)—
Can save the executionNo (recalculated on the next run)Yes -out (save plan)No
Common misconceptions① “check mode changes nothing” —check_mode: false tasks will still actually run; a custom module that claims check support without implementing it may still modify the target. ② “check shows changed=0, so the actual run also has 0 changes” — tasks that do not support check are skipped, and later tasks that depend on them may also be skipped or fail, so the conclusion is incomplete. ③ “include_tasks with tags,--tags will select the tasks inside it” — only the include itself is selected; inner tasks without that tag get skipped (so the include accomplishes nothing).

Diagram: how tags are inherited along the hierarchy

play: myapp (tags: [app]) → all tasks carry app import_tasks: config.yml (tags: [config]) Render environment file → {app, config} Render systemd unit → {app, config} Static import: expanded at parse time; tags copied to each child task --tags config ⇒ both tasks run include_tasks: smoke.yml (tags: [smoke]) The include statement itself → {app, smoke} curl /healthz → {app} (no smoke!) --tags smoke ⇒ the include runs, but the inner tasks are skipped Fix: apply: {tags: [smoke]} or tag the inner tasks
Figure 6-1 import copies tags; include only tags itself

Flowchart: the fate of a task in check mode

--checkansible_check_mode=true Task check_mode: false→ actually runs Module supports check (full)→ returns predicted changed Module does not support it (none)→ skipping + --diffshows before / after Subsequent tasks that depend on it: may fail or be skippedProtect with when: not ansible_check_mode RECAPchanged = predicted value
Figure 6-2 Three outcomes in check mode; diff only takes effect for modules that support it

Interactive simulator: which tasks will run in this execution?

The task list comes from this lesson’s site.yml (myapp play). Enter --tags,--skip-tags (comma-separated; leave empty to not specify), tick check mode, then click “Calculate” or “Play tasks one by one”. You can try: config,smoke,debug,release + skip always.

Core commands and parameters

CommandPurposeNotes
ansible-playbook site.yml --list-tagsList all tagsShows only statically visible tags (cannot see inside includes)
--list-tasks --tags configPreview the selected tasksDoes not connect to hosts
--tags a,b / --skip-tags cSelect / excludeCan be specified multiple times
--check / -CDry runUnsupported modules are skipped
--diff / -DShow differencesMost commonly used in combination with -C
--limit node3Limit hostsCombined with tags, you can achieve “minimal change”
ansible-playbook site.yml --list-tags
playbook: site.yml

  play #1 (redis): Redis	TAGS: []
      TASK TAGS: []

  play #2 (app): myapp	TAGS: []
      TASK TAGS: [always, common, config, install, release, service]
# deploy config only, and preview the differences
ansible-playbook site.yml --tags config --check --diff --limit node3
TASK [myapp : Validating arguments against arg spec main - …] ******************
ok: [node3]
TASK [myapp : Render environment file] *****************************************
ok: [node3]
TASK [myapp : Render systemd unit] *********************************************
--- before: /etc/systemd/system/myapp.service
+++ after: /home/azureuser/.ansible/tmp/…/myapp.service.j2
@@ -11,7 +11,7 @@
 EnvironmentFile=/etc/myapp.env
 WorkingDirectory=/opt/myapp/current
-ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 6 --access-logfile - app:app
+ExecStart=/opt/myapp/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 3 --access-logfile - app:app
 Restart=on-failure

changed: [node3]
RUNNING HANDLER [myapp : Restart myapp] ****************************************
changed: [node3]
PLAY RECAP *********************************************************************
node3  : ok=4  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

How to verify: After check, look at the file on the node to confirm it was not modified. Common errors: In check mode, handlers also show changed (also a prediction). The env file does not show diffs because of diff: false — this is intentional. Production use: CI runs --check --diff on PRs and posts the output as a comment.

Make tasks behave correctly in check mode too

- name: Read gunicorn version (read-only, also in check mode)
  ansible.builtin.command: "{{ myapp_home }}/venv/bin/gunicorn --version"
  register: myapp_gunicorn_version
  changed_when: false
  check_mode: false

- name: This depends on a package installed earlier in the same run
  ansible.builtin.command: some-tool --configure
  when: not ansible_check_mode

- name: Dangerous: flush redis (only when explicitly requested)
  ansible.builtin.command: redis-cli FLUSHALL
  environment: { REDISCLI_AUTH: "{{ redis_password }}" }
  no_log: true
  tags: [never, redis_flush]

- name: Smoke test (dynamic include, tags passed down with apply)
  ansible.builtin.include_tasks:
    file: smoke.yml
    apply:
      tags: [smoke]
  tags: [smoke]

Lab 6: deploy config only, rehearse changes, and debug tasks (about 5 minutes)

View the tags and preview the tasks:
cd ~/ansible-lab
ansible-playbook site.yml --list-tags
ansible-playbook site.yml --list-tasks --tags config
Change one parameter, then rehearse with check + diff:
sed -i 's/^myapp_workers: 6/myapp_workers: 3/' inventory/host_vars/node3.yml
ansible-playbook site.yml --tags config --check --diff --limit node3
ansible node3 -b -m ansible.builtin.command -a "grep -o 'workers [0-9]*' /etc/systemd/system/myapp.service"
node3 | CHANGED | rc=0 >>
workers 6

The file still says 6: check mode did not change the target.

Real run, config only::
ansible-playbook site.yml --tags config --limit node3
ansible node3 -b -m ansible.builtin.command -a "pgrep -c -f 'gunicorn.*app:app'"
node3 | CHANGED | rc=0 >>
4

1 master + 3 workers = 4 processes.

Debug task with the never tag + apply on the include: in roles/myapp/tasks/main.yml , add at the end:
- name: Dump effective myapp variables (debug only)
  ansible.builtin.debug:
    msg:
      port: "{{ myapp_port }}"
      workers: "{{ myapp_workers }}"
      version: "{{ myapp_version }}"
  tags: [never, debug]

- name: Smoke test
  ansible.builtin.include_tasks:
    file: smoke.yml
  tags: [smoke]
---
- name: GET / returns a counter
  ansible.builtin.uri:
    url: "http://127.0.0.1:{{ myapp_port }}/"
    return_content: true
  register: myapp_home_page
  failed_when: "'hits=' not in (myapp_home_page.content | default(''))"
ansible-playbook site.yml --limit node3 --tags debug
ansible-playbook site.yml --limit node3 --tags smoke
TASK [myapp : Smoke test] ******************************************************
included: /home/azureuser/ansible-lab/roles/myapp/tasks/smoke.yml for node3
PLAY RECAP *********************************************************************
node3  : ok=3  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

The include ran, but “GET / returns a counter” did not run! Add apply: { tags: [smoke] } to the include_tasks and run again to see the uri task.

Drift detection: manually edit the file on the node, then detect it with check:
ansible node2 -b -m ansible.builtin.lineinfile -a "path=/etc/myapp.env line=DEBUG=1"
ansible-playbook site.yml --check --limit node2 | tail -3
PLAY RECAP *********************************************************************
node2  : ok=22  changed=2  unreachable=0  failed=0  skipped=3  rescued=0  ignored=0

changed=2 (env file + handler) indicates drift; the skipped list includes the uri health check, which does not support check mode. Cleanup: ansible-playbook site.yml --tags config --limit node2 restore the file to the desired state.

Case 1: “minimal change” in a change window

Problem: Only one TLS certificate needs rotating, but the full playbook would also upgrade packages along the way. Approach: Tag all certificate-related tasks with tls tag, and record in the change ticket the --tags tls --limit web --check --diff preview output; after approval, remove --check and execute. Limits: Tags are only a selection mechanism; if the tls tasks depend on variables registered by other stages, running them alone will fail — dependencies must be considered when designing the role.

Case 2: nightly drift detection

Problem: Someone logs into a server and tunes parameters by hand; the next deployment overwrites them and causes an outage. Approach: A scheduled job (scheduled with AWX in Lesson 5) runs the full playbook with --check --diff , parses the RECAP, and when changed > 0 is greater than zero, sends the diff to Teams/Slack. Limits: Tasks that do not support check are skipped, so the resources they manage are not detected; the output may contain secrets, so make sure the related tasks use diff: false/no_log.

Case 3: a dangerous task triggered by mistake

Problem: The “rebuild index” task is in a role and is controlled only by when: rebuild | default(false) , and someone set rebuild to true in group_vars and forgot to change it back. Approach: Change it to tags: [never, reindex], which runs only when explicitly requested with --tags reindex to run; also require -e confirm_reindex=yes and check it with assert. Limits:--tags all It does not trigger never, but --tags never does trigger all never tasks — do not use it that way.

Common errors and fixes

After running --tags smoke, only included: …/smoke.yml is shown, and none of the tasks inside it run

Cause: Tags on include_tasks / include_role are not passed to the inner tasks.

Fix:apply: { tags: [smoke] }; or change to import_tasks (static); or tag the inner tasks with the same tag.

In check mode: fatal: [node3]: FAILED! => {"msg": "… No such file or directory: '/opt/myapp/venv/bin/gunicorn'"}

Cause: On a new host, the earlier pip install only “predicts” in check mode, so the venv does not exist and the subsequent tasks that depend on it fail.

Fix: Add when: not ansible_check_mode to tasks that depend on earlier changes; or run check only on hosts that were already deployed.

skipping: [node3] => {"msg": "remote module (ansible.builtin.uri) does not support check mode"} / "Command would have run if not in check mode"

Cause: The module’s check_mode support is none, or the command did not provide creates/removes.

Fix: Add check_mode: false + changed_when: false to read-only commands; for commands that modify the target, use creates/removes, or switch to modules with check support.

With --tags config, the error reads: 'myapp_current' is undefined

Cause: The selected task references a variable that was registered by a not-selected task.

Fix: Give the task that produces the variable the relevant tag, or add always; or use | default(...) at the reference point.

With --diff, plaintext passwords appeared in the terminal

Cause: The template / lineinfile diff contains secrets.

Fix: Add diff: false or no_log: true to the related tasks; concentrate secrets in a few files so they are easier to control centrally.

Command-line practice questions
1. List the tasks that site.yml would run with --tags release , without connecting to any host.
ansible-playbook site.yml --list-tasks --tags release
2. Rehearse all changes on the app group except the install stage, and show the differences.
ansible-playbook site.yml --limit app --skip-tags install --check --diff
Scenario analysis
The team wants every PR to include a preview of “what will change”, but check always fails on newly added hosts, and the changed counts in the RECAP on existing hosts are not trustworthy. How would you improve this?

① Run the preview only against environments that are already deployed (staging); ② review role check compatibility: tasks that depend on earlier changes get when: not ansible_check_mode, read-only commands get check_mode: false + changed_when: false, replace command/shell with modules; ③ in CI, also output the skipped task list, explicitly telling approvers “these tasks were not predicted”; ④ for the infrastructure layer that needs exact plans, hand it off to Terraform plan (the division of labor in Lesson 3, Module 6).

Instructional videos

No verified video specifically covering tags and check/diff modes was found.

Official docs

Video storyboard (about 75 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a column of task cards, each with a colored tag; after entering tags config, only two blue cards light up, along with the always cards.
Narration: tags let you run only the part you need. Tasks with the always tag always run; tasks with the never tag only run when named explicitly.
Shot 2 · 20–45s
Visual: the import box copies its tags to each child task; the include box tags only itself, with the inner tasks greyed out; after adding apply, they light up.
Narration: static imports pass tags down, dynamic includes do not — apply is needed.
Shot 3 · 45–75s
Visual: the terminal runs check with diff, showing red and green difference lines; the uri task shows skipping.
Narration: check with diff is a powerful tool for change review, but modules that do not support check are skipped, so the conclusion must be taken with a grain of salt.
or score 70% or higher on the quiz

Module 7 · ansible-lint and Molecule testing

41:00 – 51:00 · Static checks block “style problems”; Molecule proves in disposable containers that the role installs, can run repeatedly, and produces correct results
10 minansible-lint 26.11.0 · molecule 26.11.0molecule-plugins[docker] 26.11.0★★★★★
Learning objectives
  • Be able to run ansible-lint and read its output, understand the profiles (min → basic → moderate → safety → shared → production), and .ansible-lint configuration; be able to use --fix for automatic fixes, and # noqa and skip_list to make justified exemptions.
  • Understand Molecule scenarios and the test sequence: dependency → destroy → syntax → create → prepare → converge → idempotence → verify → destroy.
  • Write a Docker-driven Molecule scenario for the myapp role (systemd container), write verify in Ansible, and make the idempotence test pass.
Prerequisites: Modules 1–6 (this module puts all the earlier changes under test). Importance:★★★★★ (a role without tests should not go to production)

What: two kinds of tools

ansible-lintMolecule
TypeStatic analysis (does not connect to hosts)Integration test (actually executes)
What it findsNon-standard style, deprecated syntax, potential bugs (short names, missing name, command without changed_when, unset file permissions, variables without a prefix, YAML issues, schema errors)Whether the role installs on a clean system, whether a second run gives changed=0 (idempotence), and whether the final state is correct
SpeedSecondsMinutes (creating containers, installing software)
Where it runspre-commit + CI on every commitCI on each PR / before merge

Why: why it is needed

  • A role that “works on my machine” often depends on packages manually installed on some old server. Molecule starts from a clean image every time.
  • Idempotence is Ansible’s core promise, and the premise for drift detection (Module 6) being trustworthy; Molecule’s idempotence step verifies it automatically.
  • Lint keeps the team’s style consistent and catches deprecations caused by ansible-core upgrades early.

How: ansible-lint rules and profiles

ansible-lint has dozens of built-in rules, each belonging to a profile; the profiles are cumulative, in order: min (can be loaded correctly by Ansible) → basic (basic style) → moderate → safety (avoids uncertain results, such as package-latest) → shared (ready for publishing to Galaxy) → production (enterprise production requirements, including FQCN, etc.). The end of the output tells you the “last satisfied profile”.

Common rulesMeaningExample fix
fqcn[action-core]Built-in module used with a short nameapt → ansible.builtin.apt
name[missing] / name[casing]Task has no name / name is not capitalizedAdd it - name: Install packages
no-free-formUsed key=value syntaxChange to YAML dictionary parameters
no-changed-whencommand/shell without changed_whenAdd changed_when or switch to creates/removes
risky-file-permissionsFile created without setting modemode: "0644"
var-naming[no-role-prefix]Role variable not prefixed with the role nameapp_port → myapp_port
yaml[truthy]Used yes/noChange to true/false
schema[meta] / schema[playbook]File does not conform to the JSON schemaFix the fields in meta/main.yml
ignore-errorsUsed ignore_errorsChange to failed_when (Module 5)
command-instead-of-moduleCalling systemctl/apt etc. via commandSwitch to the corresponding module

How: Molecule scenarios and test sequence

A scenario is in molecule/<name>/ directory; its core files are molecule.yml (driver, platform, provisioner, verifier, test sequence) and converge.yml (the playbook under test),verify.yml (assertions), and optionally prepare.yml. molecule test Run the full sequence (per the default sequence of molecule 26.x):

StepWhat it does
dependencyInstall collections/roles per requirements.yml
cleanup / destroyClean up instances left over from last time
syntaxansible-playbook --syntax-check converge.yml
createDriver creates instances (docker driver: pull images, start containers)
prepareTest prerequisites (such as installing Redis dependencies)
convergeRun converge.yml (the role under test)
idempotenceRun converge again; fail if any task reports changed; tasks with the molecule-idempotence-notest tag are excluded
side_effectOptional: simulate failure/upgrade
verifyRun verify.yml (default Ansible verifier; testinfra is also supported)
cleanup / destroyRemove instances

Driver: This lesson uses the molecule-plugins[docker] driver, docker systemd test image commonly used in the community geerlingguy/docker-ubuntu2404-ansible (with systemd as PID 1, and Python and Ansible dependencies pre-installed); it requires privileged: true,cgroupns_mode: host and mounts /sys/fs/cgroup. The recent getting-started examples in the Molecule official docs emphasize the “Ansible-native” approach: driver: default plus your own create.yml/destroy.yml (the example uses the containers.podman module); both approaches work, so follow the docs of the version you installed for the exact syntax.

When: putting it into the development workflow

  • Locally: an IDE plugin while editing (the VS Code Ansible extension bundles ansible-lint) + molecule converge iterate repeatedly, and finally molecule test.
  • pre-commit: ansible-lint (the official pre-commit hooks are provided).
  • CI: lint → molecule test (matrix: multiple OS images, multiple ansible-core versions) → merge (Lesson 5).

Comparison with similar technologies

ansible-lint + MoleculeTerraformChef
Static checksansible-linttflint, terraform validateCookstyle
Integration testsMoleculeterraform test, TerratestTest Kitchen + InSpec
Idempotence testsBuilt-in idempotence stepplan shows no changeskitchen converge twice
Common misconceptions① “Passing lint means the role works” — lint executes no tasks, so it cannot catch a misspelled package name or a port conflict. ② “Testing in a container is the same as being fine on a VM” — systemd, kernel parameters (sysctl), firewalls, and SELinux in containers differ from VMs; critical roles should also be tested in a VM scenario (Molecule also supports cloud/VM drivers or delegated mode). ③ “To make idempotence pass, just add changed_when: false is enough” — this only applies to truly read-only tasks; tasks that change the system should be rewritten as idempotent implementations (creates, modules), otherwise you are hiding the problem.

Architecture diagram: Molecule docker scenario

~/ansible-lab/molecule/myapp/ molecule.ymldriver: docker · platforms prepare.ymlInstall Redis (redis role) converge.ymlinclude_role: myapp verify.ymlservice_facts + uri Test variables (no Vault dependency): provisioner.inventory.group_vars myapp_redis_host: 127.0.0.1 redis_password: molecule-test moleculeGenerate a temporary inventoryCall ansible-playbookConnection method: community.docker Docker Engine 29 (control node) Container myapp-ubuntu2404 geerlingguy/docker-ubuntu2404-ansible PID 1 = systemd (privileged) redis-server.service myapp.service (gunicorn :5000) /sys/fs/cgroup:rw · cgroupns host Each molecule test starts from a clean image docker exec
Figure 7-1 Molecule uses the docker driver to create a systemd container, then runs the role over the docker connection plugin

Flowchart: quality gates (local → CI)

Edit roleIDE live lint pre-commitansible-lint molecule convergeIterate locally CI: lintprofile production CI: molecule test (matrix)idempotence + verify → merge
Figure 7-2 The further left, the faster and cheaper; in CI, Molecule is the last line of defense before merging (the pipeline is built in Lesson 5)

Step-by-step animation: the full sequence of molecule test

Turn on the “fault switches” below, then play, and observe which step fails and what appears in the terminal.

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-lintLint the current project (auto-detects playbooks, roles, and vars files)--profile production; -f pep8|sarif|codeclimate; --offline does not install dependencies
ansible-lint --fixAuto-fix fixable rules (FQCN, YAML formatting, no-free-form, etc.)Review the git diff after fixing
ansible-lint -L / -TList rules / tags
molecule init scenario NAMEGenerate a scenario skeletonGenerated files follow the installed version; this lesson gives the complete files directly
molecule test -s myappFull test sequence--destroy never Keep instances after a failure for troubleshooting
molecule converge / idempotence / verifyRun a single stepconverge is the most commonly used during development
molecule login -s myappEnter the instance shellWith multiple instances, -h instance-name
molecule list / destroyView / delete instances
---
profile: production            # min / basic / moderate / safety / shared / production
exclude_paths:
  - collections/               # third-party collections are not ours to manage
  - .cache/
  - legacy/
  - legacy-site-v1.yml
skip_list: []                  # global exemptions must be justified in the PR
warn_list:
  - experimental
kinds:
  - playbook: "site.yml"
  - playbook: "show-vars.yml"
  - playbook: "molecule/*/*.yml"
- name: Redis
  hosts: cache
  become: yes
  tasks:
    - name: Install redis
      apt: name=redis-server state=present update_cache=yes
    - lineinfile: path=/etc/redis/redis.conf regexp='^bind ' line='bind 0.0.0.0'
      notify: restart redis
  handlers:
    - name: restart redis
      service: name=redis-server state=restarted

- name: myapp
  hosts: app
  become: yes
  tasks:
    - apt: name=python3-venv state=present update_cache=yes
    - copy: src=files/myapp/app.py dest=/opt/myapp/app.py owner=myapp
mkdir -p legacy   # save the negative example above as legacy/site-v1.yml
ansible-lint legacy/site-v1.yml --profile production
ansible-lint legacy-site-v1.yml --profile production   # Lesson 1’s site.yml (backed up in Module 1)
WARNING  Listing 21 violation(s) that are fatal
fqcn[action-core]: Use FQCN for builtin module actions (apt).
legacy/site-v1.yml:6 Use `ansible.builtin.apt` or `ansible.legacy.apt` instead.

no-free-form: Avoid using free-form when calling module actions. (apt)
legacy/site-v1.yml:6 Task/Handler: Install redis

name[missing]: All tasks should be named.
legacy/site-v1.yml:27 Task/Handler: apt name=python3-venv state=present update_cache=yes

name[casing]: All names should start with an uppercase letter.
legacy/site-v1.yml:20 Task/Handler: restart redis

risky-file-permissions: File permissions unset or incorrect.
legacy/site-v1.yml:30 Task/Handler: copy src=files/app.py dest=/opt/myapp/app.py owner=myapp
...
                  Rule Violation Summary
 count tag                    profile    rule associated tags
     2 risky-file-permissions safety     unpredictability
     7 name[missing]          basic      idiom
     8 fqcn[action-core]      production formatting
     4 no-free-form           basic      syntax, risk
Failed: 21 failure(s), 0 warning(s) on 1 files. Last profile that met the validation criteria was 'min'.

Lesson 1’s site.yml already uses FQCN and names every task, so there will be far fewer violations (possibly leaving some yaml,name[play] formatting-type issues, depending on the actual output); its real problem is structural — lint cannot detect “no roles, no tests, no rollback”, which the rest of this lesson’s modules address.

How to verify: Running the refactored project ansible-lint should output “Passed: 0 failure(s), 0 warning(s)… Profile 'production' was required, but 'production' profile passed.” (the exact wording depends on the version). Common errors: ansible-lint tries to install the dependencies in requirements.yml and write them to the cache before running; in an offline environment you need --offline. Production use:-f sarif The output can be uploaded to GitHub code scanning.

# Justified local exemption: written at the end of the line, with the reason stated
- name: Record deployment attempt   # noqa: risky-file-permissions  (example; this lesson’s task already sets mode)
  ansible.builtin.lineinfile: …

Lab 7: add lint and Molecule to the myapp role (about 10 minutes)

Lint the whole project and fix:
cd ~/ansible-lab
# write the .ansible-lint from the Commands page
ansible-lint
ansible-lint --fix          # auto-fix the fixable items, then review with git diff

This lesson’s role code was written to the production profile; common remaining issues: show-vars.yml : the debug task names, and the lineinfile regex escaping in the redis role (yaml rule),var-naming. Fix them one by one until the lint passes.

Create the Molecule scenario directory and configuration:
mkdir -p molecule/myapp
---
dependency:
  name: galaxy
  options:
    requirements-file: requirements.yml
driver:
  name: docker
platforms:
  - name: myapp-ubuntu2404
    image: geerlingguy/docker-ubuntu2404-ansible:latest
    pre_build_image: true
    privileged: true
    cgroupns_mode: host
    volumes:
      - /sys/fs/cgroup:/sys/fs/cgroup:rw
    command: ""                       # use the image’s default CMD (systemd)
    groups:
      - app
      - cache
provisioner:
  name: ansible
  env:
    ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/roles
  inventory:
    group_vars:
      all:
        redis_password: molecule-test          # test value; does not use Vault
        myapp_redis_password: molecule-test
        myapp_redis_host: 127.0.0.1
        common_timezone: UTC
verifier:
  name: ansible
scenario:
  test_sequence:
    - dependency
    - destroy
    - syntax
    - create
    - prepare
    - converge
    - idempotence
    - verify
    - destroy

${MOLECULE_PROJECT_DIRECTORY} is an environment variable provided by Molecule (the project root directory where molecule runs), and molecule.yml supports environment variable substitution. In the test, we deliberately do not load the group_vars and Vault under inventory/; tests must be able to run in CI without production secrets.

prepare / converge / verify:
---
- name: Prepare (Redis dependency on the same instance)
  hosts: all
  become: true
  gather_facts: true
  roles:
    - role: redis
---
- name: Converge
  hosts: all
  become: true
  gather_facts: true
  tasks:
    - name: Include myapp role
      ansible.builtin.include_role:
        name: myapp
---
- name: Verify
  hosts: all
  become: true
  gather_facts: false
  tasks:
    - name: Collect service facts
      ansible.builtin.service_facts:

    - name: Services are running and enabled
      ansible.builtin.assert:
        that:
          - ansible_facts.services['myapp.service'].state == 'running'
          - ansible_facts.services['myapp.service'].status == 'enabled'
          - ansible_facts.services['redis-server.service'].state == 'running'

    - name: Health endpoint returns 200
      ansible.builtin.uri:
        url: http://127.0.0.1:5000/healthz
        status_code: 200

    - name: Unit file uses the default worker count
      ansible.builtin.command: grep -c -- "--workers 2 " /etc/systemd/system/myapp.service
      register: myapp_unit_grep
      changed_when: false
      failed_when: myapp_unit_grep.stdout | int != 1

    - name: Env file is not world-readable
      ansible.builtin.stat:
        path: /etc/myapp.env
      register: myapp_env_stat
      failed_when: myapp_env_stat.stat.mode != '0640'
Mark tasks that are “intentionally non-idempotent”: the Module 5 deployment record task appends a line every time. In roles/myapp/tasks/release.yml , add the tag to the always task:
  always:
    - name: Record deployment attempt
      ansible.builtin.lineinfile:
        …
      tags: [molecule-idempotence-notest]
Development loop: converge → enter the instance to inspect → full test:
molecule converge -s myapp
molecule login -s myapp            # inside the container: systemctl status myapp; exit to leave
molecule test -s myapp
INFO     myapp ➜ discovering: Found 1 scenario(s)
INFO     myapp ➜ dependency: Executing
INFO     myapp ➜ create: Executing
...
PLAY RECAP *********************************************************************
myapp-ubuntu2404 : ok=27  changed=15  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
INFO     myapp ➜ idempotence: Executing
...
myapp-ubuntu2404 : ok=27  changed=0   unreachable=0  failed=0  skipped=2  rescued=0  ignored=0
INFO     myapp ➜ idempotence: Executed: Successful
INFO     myapp ➜ verify: Executing
TASK [Health endpoint returns 200] *********************************************
ok: [myapp-ubuntu2404]
INFO     myapp ➜ verify: Executed: Successful
INFO     myapp ➜ destroy: Executed: Successful

The log format changes with the Molecule version; what matters is that idempotence and verify show success.

Deliberately break idempotence and see how the test fails: in roles/myapp/tasks/service.yml , at the end, temporarily add a command without changed_when:
- name: Print gunicorn version
  ansible.builtin.command: "{{ myapp_home }}/venv/bin/gunicorn --version"
molecule converge -s myapp && molecule idempotence -s myapp
CRITICAL Idempotence test failed because of the following tasks:
*  => myapp : Print gunicorn version

ansible-lint also reports no-changed-when. Adding changed_when: false and running the test again will pass. Cleanup: molecule destroy -s myapp.

Case 1: a compatibility matrix before an OS upgrade

Problem: The company plans to migrate from Ubuntu 22.04 to 24.04, but is not sure whether 30 roles are compatible. Approach: Each role’s Molecule scenario parameterizes the image with an environment variable (image: "geerlingguy/docker-${MOLECULE_DISTRO:-ubuntu2404}-ansible:latest"), and CI uses a matrix to run 2204 and 2404 at the same time, so failing roles are obvious at a glance. Limits: Container images still differ from cloud vendors’ VM images (cloud-init, kernel); critical roles should add a VM scenario.

Case 2: resistance to rolling out lint rules

Problem: The first run of the production profile on an old repository reported 800 issues, and the team refused to enable it. Approach: Start with min/basic and enforce it in CI; use ansible-lint --generate-ignore to generate .ansible-lint-ignore to freeze existing issues; new code must comply, and each iteration works through part of the ignore list. Limits: The ignore file must be reviewed regularly, or it becomes permanent.

Case 3: Molecule uncovers a “hidden dependency”

Problem: The role always worked on the old server, but Molecule fails on a clean image: pip the module reports the venv cannot be found; the old server had python3-venv installed by hand. Approach: Write the dependency into the role’s vars (myapp_packages), and merge after Molecule passes. Limits: If the test image is “too fat” (with many packages preinstalled), it will equally hide hidden dependencies, so choose a slim image where possible.

Common errors and fixes

CRITICAL Idempotence test failed because of the following tasks: * => myapp : Record deployment attempt

Cause: In the second converge, some tasks still report changed.

Fix: Decide whether the task should “change every time”: if yes, add the molecule-idempotence-notest tag; if no, fix the implementation (use a module instead of command, add creates, a correct changed_when, and do not put timestamps in templates).

System has not been booted with systemd as init system (PID 1). Can't operate. / Failed to connect to bus: No such file or directory

Cause: The container was not started with systemd: wrong image,command overrides CMD, or the privileged / cgroup mounts are missing.

docker inspect myapp-ubuntu2404 --format '{{.Config.Cmd}} {{.HostConfig.Privileged}} {{.HostConfig.CgroupnsMode}}'
docker exec myapp-ubuntu2404 ps -p 1 -o comm=

Fix: Use a systemd image; set privileged: true,cgroupns_mode: host, mount /sys/fs/cgroup:rw,command: "". Note that docker inspect’s {{ }} is a Go template.

CRITICAL Failed to pre-validate. … Unable to find driver 'docker' / Driver docker is not available

Cause: The docker plugin of molecule-plugins is not installed, or it was installed into another Python environment; or the Docker daemon is unreachable.

molecule drivers
pipx runpip ansible list | grep -i molecule
docker info --format '{{.ServerVersion}}'

Fix:pipx inject ansible "molecule-plugins[docker]"; confirm the current user is in the docker group.

ERROR! the role 'myapp' was not found in …/molecule/myapp/roles:…

Cause: converge.yml lives in the scenario directory, and the default roles search path does not include the project’s roles/.

Fix: In molecule.yml’s provisioner.env section, set ANSIBLE_ROLES_PATH: ${MOLECULE_PROJECT_DIRECTORY}/roles, and run molecule from the project root directory.

ansible-lint: WARNING Unable to install collection … / syntax-check[unknown-module]: couldn't resolve module/action 'community.general.timezone'

Cause: The lint pre-run step needs to install the collections in requirements.yml, but the environment has no network access; or --offline was used but the corresponding collection is not installed locally.

Fix: First ansible-galaxy collection install -r requirements.yml -p ./collections; in an offline environment, use --offline and preinstall the dependencies, or use mock_modules as a last resort.

Command-line practice questions
1. Check the project with the production profile, and write the output to a file in SARIF format.
ansible-lint --profile production -f sarif > ansible-lint.sarif
2. Run the complete test for the myapp scenario, keeping the containers for troubleshooting if it fails.
molecule test -s myapp --destroy never
molecule login -s myapp
Scenario analysis
Molecule passes locally, but in CI (GitHub Actions ubuntu runner), all systemd-related tasks fail in the converge stage. How would you troubleshoot this?

① Confirm that Docker on the runner supports privileged and cgroup v2 (the ubuntu runner uses cgroup v2 by default, so you need cgroupns_mode: host and /sys/fs/cgroup:rw); ② in CI, add docker exec … ps -p 1 to check PID 1; ③ confirm the image tag is consistent (do not let latest drift; pin the digest in CI); ④ compare whether the molecule, molecule-plugins, and community.docker versions match the local ones (same requirements file, or the same EE / ansible-dev-tools version).

Verified teaching videos

▶
Ansible 101 - Episode 7 - Molecule Testing and Linting and Ansible Galaxy — Jeff Geerling
2020 livestream series · English · about 1 hour · introduction to yamllint/ansible-lint and Molecule (Molecule 3.x at the time; for command and config details, follow this lesson and the current docs)
▶
Ansible 101 - Episode 8 - Playbook testing with Molecule and GitHub Actions CI — Jeff Geerling
2020 livestream series · English · running Molecule in CI, using the systemd images maintained by the author docker-*-ansible (same family as the images used in this lesson)

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: ansible-lint scans an old playbook; red labels such as fqcn, name missing, and no free form pop up on screen, and finally last profile min is shown.
Narration: ansible-lint is a static check; it finds style problems in seconds and tells you how far you are from production standards.
Shot 2 · 20–50s
Visual: Molecule’s step bar lights up in sequence: dependency, create, prepare, converge; a systemd container appears and starts myapp.
Narration: Molecule starts from a clean container every time and really executes the role.
Shot 3 · 50–75s
Visual: the idempotence step runs converge again; one task turns yellow, with CRITICAL Idempotence test failed.
Narration: if the second run still makes changes, the idempotence test fails — this is Ansible’s core promise.
Shot 4 · 75–90s
Visual: the assertions in verify all turn green, and the container is destroyed.
Narration: verify checks the final state, and then everything is cleaned up.
or score 70% or higher on the quiz

Module 8 · Execution environments and ansible-navigator

51:00 – 60:00 · Install ansible-core, collections, Python dependencies, and system tools together into a container image: anyone, any pipeline, and AWX/AAP use the same “runtime”
9 minansible-builder 3.2.0 · ansible-navigator 26.11.0EE definition file version 3★★★★☆
Learning objectives
  • Explain what problems an Execution Environment (EE) solves: control-node dependency drift, “it runs on my laptop”, and AWX/AAP inconsistency with local runs.
  • Write execution-environment.yml (version 3): base_image, ansible_core, ansible_runner, galaxy, python, and system dependencies; understand the multi-stage build that ansible-builder generates (base → galaxy → builder → final).
  • Use ansible-navigator run to run myapp’s site.yml in an EE; configure ansible-navigator.yml (image, pull policy, network, mounts, environment variables, playbook artifact) and troubleshoot common problems.
Prerequisites: Images and containers from the Docker course; requirements.yml from Module 2. Importance:★★★★☆ (AWX/AAP only accepts EEs; a prerequisite for Lesson 5)

What: what an execution environment is

Execution Environment (EE) is a container image that follows conventions. It contains a specified version of Python, ansible-core, ansible-runner (responsible for starting playbooks in a standard way and producing events/artifacts), the collections you need, and their Python/system dependencies (such as the az CLI, psycopg, and the kubernetes client). Toolchain:

ToolPurposeVersion as of 2026-11
ansible-builderReads execution-environment.yml, generates the build context (Containerfile) and calls podman/docker to build the EE3.2.0 (2026-10-13, requires Python ≥ 3.11)
ansible-navigatorRuns playbooks in the EE container (run), browses collections/docs/inventory, and replays artifacts; has a TUI (interactive) mode and a stdout mode26.11.0 (2026-11-05)
ansible-runnerThe entry point inside the EE; AWX/AAP also run jobs through itInstalled inside the EE
AWX / AAP 2.6Uses the EE as the job runtime (Lesson 5)Since AAP 2.7, containerized installation only

Why: why it is needed

  • Dependency hell: azure.azcollection needs dozens of azure-* Python packages, and kubernetes.core needs the kubernetes client… installed in a venv on the control node, they quickly conflict with other projects.
  • Reproducibility: Module 2 solved collection versions, but the ansible-core, Python, and system package versions can still differ; the EE image fixes all of them and can be referenced by digest.
  • Consistency: Developers’ laptops, CI runners, and AWX/AAP run the same image, so the “works locally, fails on the platform” problem disappears.

How: ansible-builder build stages

  1. ansible-builder create: validates the definition file and, under context/ , generates Containerfile and _build/ (copies requirements.yml, requirements.txt, bindep.txt, and helper scripts).
  2. base stage: starts from base_image , installs python_interpreter (system packages), plus ansible-core and ansible-runner (via pip).
  3. galaxy stage: ansible-galaxy collection install -r requirements.yml installs collections (the build needs access to Galaxy / a private Hub).
  4. builder stage: aggregates the Python dependencies bundled with collections (requirements.txt), the system dependencies (bindep.txt), and those declared in your definition, and builds wheels.
  5. final stage: copies from base, installs system packages and wheels, copies the collections, and sets up the user (default UID 1000) and the entrypoint.
  6. ansible-builder build = create + calls the container engine to build (--container-runtime docker|podman, podman by default). ansible-builder requires an RPM-based (dnf/microdnf) base image.

How: what ansible-navigator run does

  1. Reads settings (command line > environment variables ANSIBLE_NAVIGATOR_* > settings file: ANSIBLE_NAVIGATOR_CONFIG ansible-navigator.yml, project directory ansible-navigator.yml,~/.ansible-navigator.yml), use ansible-navigator settings --effective to view the final values.
  2. Prepare the image according to the pull policy (always / missing / never / tag).
  3. Start the container: (the project directory) is mounted at the same path as the working directory; if SSH_AUTH_SOCK exists, mount the ssh-agent socket, plus your configured volume-mounts, environment variables, and container options (such as --network=anslab).
  4. Inside the container, ansible-runner runs ansible-playbook, the event stream flows back to navigator and is shown as TUI or stdout, and (by default) the playbook artifact JSON is saved, after which you can ansible-navigator replay.

When: when to use

  • A project with many collections or Python packages, that must run in AWX/AAP, or that involves multi-person collaboration → use an EE.
  • Simple personal scripts → a pipx-installed ansible is fine too; but in CI an EE is still recommended (or at least pinned requirements).
  • EE images should be versioned like application images (myapp-ee:1.0.0), scanned for vulnerabilities, pushed to an image registry, and referenced by a pinned tag or digest in ansible-navigator.yml / AWX.

Comparison with similar technologies

EE + navigatorpipx venvWrite your own Dockerfile to install ansible
Dependency resolutionAutomatically aggregates the Python/system dependencies declared by collectionsManualManual
AWX/AAP compatibilityNativeNot applicableMust follow EE conventions (runner, user, entrypoint)
Usage experiencenavigator handles mounts, agent, and artifactsMost directYou must write the docker run parameters yourself
Common misconceptions① “The control node can SSH to 172.30.0.x, so the EE container naturally can too” — EE containers attach to Docker’s default bridge by default, while managed nodes are on a user-defined network anslab ; Docker’s network isolation rules drop traffic between the two bridges, so the EE container must join the same network (--network=anslab), or use --net=host to route through the host. ② “If a collection is installed in the EE, it will certainly be used” — if the project directory still has ./collections (Module 2), then because the project directory is mounted into the container and playbook-adjacent paths take precedence, the project’s version is used at runtime. ③ “navigator is just ansible-playbook with a UI” — its core is running inside a container; you can also --ee false turn off the EE and run the local ansible directly, but that defeats the purpose.

Architecture diagram: ansible-builder multi-stage build

Inputs execution-environment.yml (v3) requirements.yml (collections) requirements.txt (Python) bindep.txt (system packages) + the requirements.txt / bindep.txt basepython3.12 + core + runner galaxycollection install builderaggregated dependencies → wheels finalUSER 1000 myapp-ee:1.0.0ansible-core 2.21.xcommunity.general 14.0.1ansible.posix 2.2.2 … Image registryACR / GHCR / quaytag + digestVulnerability scan ConsumersDevelopers with navigatorCI runnerAWX / AAP (Lesson 5)
Figure 8-1 ansible-builder turns the definition file into a multi-stage build that produces an EE image that runs anywhere

Flowchart: runtime of ansible-navigator run

Control node (host machine) ~/ansible-lab (project directory)ansible-navigator.ymlSSH_AUTH_SOCK (ssh-agent)~/.vault/dev.passDocker Engine 29artifacts/*.json ← results EE container (--network=anslab) project directory mounted at the same path (working directory) agent socket mounted · /vault (read-only) ANSIBLE_VAULT_IDENTITY_LIST=dev@/vault/dev.pass ansible-runner → ansible-playbook site.yml event stream → navigator (stdout / TUI) Managed nodes172.30.0.11:22 node1172.30.0.12:22 node2172.30.0.13:22 node3(Docker network anslab) SSH
Figure 8-2 navigator is responsible for “connecting what is on the host into the container”: the project, the agent, password files, and the network

Step-by-step animation: from the definition file to running site.yml in an EE

Choose a common “pitfall” and play, then observe at which step it surfaces and what the error looks like; choose “all correct” to see the full flow.

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-builder createGenerate only the build context context/-f execution-environment.yml,-c context
ansible-builder build -t IMGGenerate the context and build the image--container-runtime docker; -v 3 verbose output; --build-arg; --no-cache
ansible-navigator run PLAYBOOKRun a playbook in the EE--eei IMG (image); --ce docker; -m stdout; --pp missing; --co="--network=anslab"; other parameters are passed as-is to ansible-playbook (-i,--limit,--tags,--check)
ansible-navigator exec -- CMDRun arbitrary commands in the EEexec -- ansible --version,exec -- ansible-galaxy collection list
ansible-navigator images / collections / doc / inventoryBrowse EE contentsTUI by default; add -m stdout for text output
ansible-navigator settings --effectiveShow the final effective settings and their sourcesTroubleshoot whether the settings file is being read
ansible-navigator replay FILE.jsonReplay a playbook artifactPost-mortem review, sharing a failure scene
---
version: 3
images:
  base_image:
    name: docker.io/redhat/ubi9:latest
dependencies:
  python_interpreter:
    package_system: python3.12
    python_path: /usr/bin/python3.12
  ansible_core:
    package_pip: ansible-core==2.21.*
  ansible_runner:
    package_pip: ansible-runner
  galaxy: requirements.yml
  python:
    - jmespath                        # example: the json_query filter needs this
  system:
    - openssh-clients [platform:rpm]
    - git-core [platform:rpm]
options:
  package_manager_path: /usr/bin/dnf
  tags:
    - myapp-ee:1.0.0
additional_build_steps:
  append_final:
    - LABEL org.opencontainers.image.source="https://example.internal/ansible-lab"

Note: ansible-core 2.21 requires Python 3.12–3.14, while the default python3 in UBI9 is 3.9, so you must use python_interpreter to specify 3.12 (depending on the package name actually available in the UBI9 repositories). ansible-builder only supports RPM-based base images; Red Hat subscribers usually build on the ee-minimal image provided by AAP. tags You can also specify it on the command line with -t .

ansible-builder build -f execution-environment.yml -t myapp-ee:1.0.0 --container-runtime docker -v 3
docker images myapp-ee
ls context/
Running command:
  docker build -f context/Dockerfile -t myapp-ee:1.0.0 context
...
Complete! The build context can be found at: /home/azureuser/ansible-lab/context
REPOSITORY   TAG     IMAGE ID       CREATED          SIZE
myapp-ee     1.0.0   3f9c1d2a7b44   20 seconds ago   612MB
Dockerfile  _build

How to verify:ansible-navigator exec --eei myapp-ee:1.0.0 --ce docker --pp never -- ansible --version Shows core 2.21.x and python 3.12. Common errors: The galaxy stage cannot reach Galaxy (proxy / intranet); configure ansible.cfg or --build-arg; when using docker, the generated file is named Dockerfile; with podman it is Containerfile. Production use: Build the EE in CI, scan it, push it to ACR, and output the digest for AWX to reference.

---
ansible-navigator:
  execution-environment:
    enabled: true
    container-engine: docker
    image: myapp-ee:1.0.0
    pull:
      policy: missing
    container-options:
      - "--network=anslab"             # join the same Docker network as the managed nodes
    volume-mounts:
      - src: "~/.vault"
        dest: "/vault"
    environment-variables:
      set:
        ANSIBLE_VAULT_IDENTITY_LIST: "dev@/vault/dev.pass"
  mode: stdout
  playbook-artifact:
    enable: true
    save-as: "{playbook_dir}/artifacts/{playbook_name}-artifact-{time_stamp}.json"
  logging:
    level: warning
    file: /tmp/ansible-navigator.log

Setting key names follow ansible-navigator settings --sample — the generated sample is authoritative. The environment variable ANSIBLE_VAULT_IDENTITY_LIST takes precedence over the vault_identity_list in ansible.cfg, so the container uses the /vault path.

Lab 8: build myapp-ee and deploy it with ansible-navigator (about 9 minutes)

Write the definition file and build (see the Commands page for content):
cd ~/ansible-lab
ansible-builder build -f execution-environment.yml -t myapp-ee:1.0.0 --container-runtime docker -v 3
echo "context/" >> .gitignore
Check the EE contents:
ansible-navigator exec --eei myapp-ee:1.0.0 --ce docker --pp never -- ansible --version
ansible-navigator collections --eei myapp-ee:1.0.0 --ce docker --pp never -m stdout | head -20
ansible [core 2.21.5]
  ...
  python version = 3.12.x (main, …) [GCC …] (/usr/bin/python3.12)
---
- ansible.posix: 2.2.2
- community.docker: 5.4.0
- community.general: 14.x.x
...

The community.general version is whatever gets >=14.0.0,<15.0.0 resolved to the latest version at build time — which is why production should pin exact versions.

Keep runs inside the EE from being affected by the project’s collections: the project directory is mounted into the container,./collections and playbook-adjacent paths take the highest precedence. To verify that the EE’s collection is really used, temporarily rename it:
mv collections collections.local
Write ansible-navigator.yml, load ssh-agent, and run:
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/ansible_lab
ansible-navigator settings --effective -m stdout | grep -E "image|container-options|policy" | head
ansible-navigator run site.yml --check --diff --limit node3
ansible-navigator run site.yml
PLAY [Redis] *******************************************************************
TASK [Gathering Facts] *********************************************************
ok: [node1]
...
PLAY RECAP *********************************************************************
node3  : ok=24  changed=0  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
node2  : ok=24  changed=0  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
node1  : ok=6   changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

changed=0: the same code runs in the EE and produces results matching the local machine (idempotent). The private_key_file = ~/.ssh/ansible_lab does not exist inside the container (the container’s HOME differs), so ssh warns “Identity file … not accessible” and uses keys from the agent instead; you can also mount the key into the container with volume-mounts, then point to the mounted path with the environment variable ANSIBLE_PRIVATE_KEY_FILE to the mounted path. Because the deployment record task in always would show changed if the release stage ran, the symlink task in block reports ok here, since the version was not changed.

Replay the artifact:
ls artifacts/
ansible-navigator replay artifacts/site-artifact-*.json -m stdout | tail -5
(optional) push to Azure Container Registry:
az acr login -n acransiblelab
docker tag myapp-ee:1.0.0 acransiblelab.azurecr.io/myapp-ee:1.0.0
docker push acransiblelab.azurecr.io/myapp-ee:1.0.0
docker inspect --format '{{index .RepoDigests 0}}' acransiblelab.azurecr.io/myapp-ee:1.0.0

Cost: ACR Basic is about 5 USD per month (per the Azure pricing page); AcrPush permission is required. Cleanup: mv collections.local collections restore the local collection; when not in use, docker rmi myapp-ee:1.0.0, ACR uses az acr delete -n acransiblelab or delete the resource group it is in.

Case 1: the EE pipeline of the Azure automation team

Problem: On five engineers’ laptops, the azure.azcollection version and the azure-* Python packages all differ, so results vary. Approach: The repository maintains execution-environment.yml, and when merging to main, CI builds the EE (tag = semantic version + git sha), Trivy scans it, and it is pushed to ACR; ansible-navigator.yml and AWX both reference the same tag. Limits: azure.azcollection has many dependencies, so the image is large (on the order of 1 GB); layered caching and periodic rebuilds are needed to pick up security patches.

Case 2: building inside the intranet

Problem: The build machine cannot reach galaxy.ansible.com or PyPI. Approach: In the galaxy stage, pass additional_build_files to inject an ansible.cfg pointing to the Private Automation Hub; pip uses an internal mirror (PIP_INDEX_URL build argument); the base image comes from an internal registry. Limits: Tokens must not be written into image layers; inject them with build arguments or build-time secrets, and do not keep them in the final stage.

Case 3: “works locally, fails in AWX”

Problem: The playbook succeeds on the local machine, but in AWX it reports a missing Python library for a module. Approach: Also switch local runs to navigator with the same EE as AWX; the problem reproduces immediately; add the missing library to dependencies.python and rebuild. Limits: AWX injects credentials differently (environment variables, files) from local mounts, which must be unified in Lesson 5.

Interactive troubleshooting decision tree (all topics in this lesson)

Choose step by step starting from the symptom. Covers roles, collections, variables, Vault, error handling, lint/Molecule, and EE/navigator.

Common errors and fixes

fatal: [node3]: UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: ssh: connect to host 172.30.0.12 port 22: Connection timed out"} (appears only in navigator)

Cause: EE containers default to Docker’s default bridge, while managed nodes are on the anslab network; Docker’s network isolation rules drop traffic between the two bridges (running ansible-playbook locally works, because the host can route directly to 172.30.0.0/24).

Fix:container-options: ["--network=anslab"] (or --co="--network=anslab"); you can also use --net=host to let the container use the host network.

ERROR! Attempting to decrypt but no vault secrets found (appears only in navigator)

Cause: The ansible.cfg dev@~/.vault/dev.pass entry does not exist inside the container (the container’s HOME differs, and the directory is not mounted).

Fix: Use volume-mounts to mount ~/.vault to /vault, and set the environment variable ANSIBLE_VAULT_IDENTITY_LIST=dev@/vault/dev.pass; in CI, inject it from secrets instead.

ERROR: Ansible requires Python 3.12 or newer on the controller. Current version: 3.9.x

Cause: The EE base image’s Python version is too old (the ansible-core 2.21 control node needs 3.12–3.14). During the build stage, pip may also directly report “No matching distribution found for ansible-core==2.21.*”.

Fix: In the definition file, set python_interpreter.package_system / python_path to 3.12; or switch to a base image that ships a newer Python.

Error: … Cannot connect to the Docker daemon / Error: executable file `podman` not found in $PATH

Cause: ansible-builder uses podman by default, and navigator’s default container engine is auto (podman first), but this machine only has docker; or the docker daemon is unavailable.

Fix: For ansible-builder, add --container-runtime docker; for navigator, set container-engine: docker; confirm docker info works and the user is in the docker group.

Image myapp-ee:1.0.0 could not be pulled / Error: pull access denied for myapp-ee

Cause: The locally built image was not pushed to a registry, while the pull policy is always (or the tag strategy for the latest tag).

Fix: For local images, use pull.policy: missing or never; when sharing, push to a registry and use the full image name.

Command-line practice questions
1. Build the EE with docker, tagging it as myapp-ee:1.1.0, and output detailed logs.
ansible-builder build -f execution-environment.yml -t myapp-ee:1.1.0 --container-runtime docker -v 3
2. Without using a settings file, use command-line parameters to run the config tag of site.yml against node3 in the EE in stdout mode.
ansible-navigator run site.yml --eei myapp-ee:1.1.0 --ce docker --pp never -m stdout \
  --co="--network=anslab" --limit node3 --tags config
Scenario analysis
The team decided everyone runs with navigator + EE. A month later, someone reports: “The EE clearly has community.general 14.0.1, but the errors at runtime look like an old version.” What are the possible causes, and how would you fix it?

The project directory is mounted into the container, and the project still contains ./collections (or ansible.cfg’s collections_path points to another mounted directory), and playbook-adjacent paths take precedence over the collections installed in the EE. Use ansible-navigator exec -- ansible-galaxy collection list to check the version in each path. Convention: when using an EE, do not keep collections/ in the project (add it to .gitignore and delete it in CI), or remove ./collections from the EE-specific ansible.cfg.

Instructional videos

No verified dedicated video on ansible-builder / ansible-navigator was found (the official docs mention demo videos, but the specific links could not be verified). For AWX background, you may refer to Jeff Geerling’s “Ansible 101 - Episode 10 - Ansible Tower and AWX” (iKmY4jEiy_A, verified); note that it was recorded before EEs existed.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: three laptops each show different ansible and collection versions, and the same playbook gives different results.
Narration: dependencies on the control node drift. An execution environment packs the runtime into one image.
Shot 2 · 20–50s
Visual: the execution environment yml goes into ansible-builder, passing through the base, galaxy, builder, and final stages in turn, producing the myapp-ee image.
Narration: ansible-builder aggregates the collections and their Python and system dependencies, using a multi-stage build to produce the image.
Shot 3 · 50–75s
Visual: ansible-navigator run starts the container; arrows for the project directory, ssh agent, and vault password connect into the container, and the container reaches the three nodes via the host network.
Narration: navigator connects the host’s project, keys, and network into the container, and runs the playbook inside it.
Shot 4 · 75–90s
Picture: the same image icon appears in three places: the laptop, CI, and AWX.
Narration: developers, the pipeline, and AWX use the same image, so the results are consistent.
or score 70% or higher on the quiz

Command cheat sheet

ansible-core 2.21 · From “It Works” to “Production-Ready” · every code block can be copied with one click
After-class reference

Role

ansible-galaxy role init NAME --init-path roles
ansible-galaxy role list -p roles
ansible-doc -t role -r roles NAME
ansible-playbook site.yml --list-tasks
ansible-playbook site.yml --syntax-check
# include_role: { name: x, tasks_from: config, apply: { tags: [t] } }
# meta/main.yml → dependencies: [ { role: common } ]

Collections

ansible-galaxy collection install -r requirements.yml -p ./collections
ansible-galaxy collection install -r requirements.yml -p ./collections -U
ansible-galaxy collection list community.general
ansible-galaxy collection download -r requirements.yml -p ./offline
ansible-galaxy collection install -r offline/requirements.yml -p ./collections --offline
ansible-galaxy collection verify ansible.posix -p ./collections
ansible-doc -l community.general

Variables

ansible-inventory --host node3 --yaml
ansible-inventory --graph --vars
ansible-playbook site.yml -e '{"myapp_workers": 8}'
ansible-playbook site.yml -e @overrides.yml
# debug: msg="{{ x }} ({{ x | type_debug }})"
# Merge dictionaries: {{ defaults | combine(overrides, recursive=true) }}
# 2.19+: when: x | length > 0   (conditions must be boolean)

Vault

ansible-vault create|edit|view|encrypt|decrypt FILE
ansible-vault encrypt_string --vault-id dev@prompt --stdin-name vault_x
ansible-vault rekey --vault-id dev@old --new-vault-id dev@new FILE
ansible-playbook site.yml --vault-id dev@~/.vault/dev.pass --vault-id prod@./vault-pass-client.sh
# ansible.cfg: vault_identity_list / vault_encrypt_identity / vault_id_match
# Tasks: no_log: true · diff: false · loop_control.label

Error handling

- block: [...]
  rescue:
    - ansible.builtin.debug: { msg: "{{ ansible_failed_task.name }}" }
    - ansible.builtin.fail: { msg: rolled back }
  always: [...]
# changed_when: false · failed_when: r.rc not in [0, 1]
# until: r.status == 200 · retries: 10 · delay: 2
# play: any_errors_fatal: true · serial: 1 · max_fail_percentage: 0

Tags / check / diff

ansible-playbook site.yml --list-tags
ansible-playbook site.yml --list-tasks --tags config
ansible-playbook site.yml --tags config --check --diff --limit node3
ansible-playbook site.yml --skip-tags install
ansible-playbook site.yml --tags debug      # runs tasks with never + debug
# check_mode: false · when: not ansible_check_mode

ansible-lint / Molecule

ansible-lint --profile production
ansible-lint --fix
ansible-lint -f sarif > lint.sarif
molecule test -s myapp
molecule converge -s myapp; molecule login -s myapp
molecule idempotence -s myapp; molecule verify -s myapp
molecule test -s myapp --destroy never; molecule destroy -s myapp

EE / navigator

ansible-builder build -f execution-environment.yml -t myapp-ee:1.0.0 --container-runtime docker -v 3
ansible-navigator exec --eei myapp-ee:1.0.0 --ce docker --pp never -- ansible --version
ansible-navigator run site.yml -m stdout --co="--network=anslab"
ansible-navigator settings --effective -m stdout
ansible-navigator collections -m stdout
ansible-navigator replay artifacts/site-artifact-*.json

Quick troubleshooting table

SymptomCheck firstCommon causes
the role 'x' was not foundansible-galaxy role list -p rolesroles_path, spelling, running from another directory
couldn't resolve module/actionansible-galaxy collection listShort names, collection not installed, path not in collections_path
Changed variable has no effectdebug inside the play,grep -rnrole vars / set_fact / -e overrides; dictionaries replaced as a whole
Conditionals must have a boolean resultCheck the conditional expression2.19+ strict conditionals: add | bool / | length > 0
no vault secrets found / Decryption failedhead -1 vault.yml Check the tagsNo password provided, wrong password, vault_id_match label mismatch
CI shows success after rescueCheck RECAP rescuedMissing fail at the end of rescue
Tasks inside an include not run after --tags--list-tasksinclude does not inherit tags; apply is needed
Idempotence test failedCheck the listed taskscommand without changed_when, template with timestamps, audit task without notest
systemd does not work in Moleculedocker exec … ps -p 1Image / privileged / cgroup mount
UNREACHABLE in navigatorsettings --effectiveMissing --network=anslab, ssh agent not loaded

For the full interactive troubleshooting flow, see Module 8 → Troubleshooting → decision tree.

Recommended config snippet: production project skeleton

[defaults]
inventory = inventory/hosts.ini
remote_user = ansible
private_key_file = ~/.ssh/ansible_lab
interpreter_python = auto_silent
forks = 10
retry_files_enabled = False
# this lesson’s additions
roles_path = ./roles
collections_path = ./collections:~/.ansible/collections:/usr/share/ansible/collections
vault_identity_list = dev@~/.vault/dev.pass
vault_encrypt_identity = dev

[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
pipelining = False
~/ansible-lab/
├── ansible.cfg  ansible-navigator.yml  execution-environment.yml  requirements.yml  .ansible-lint
├── site.yml
├── inventory/{hosts.ini, group_vars/{all/{main.yml,vault.yml}, app.yml}, host_vars/node3.yml}
├── roles/{common, redis, myapp}/{defaults,vars,tasks,handlers,templates,files,meta}
└── molecule/myapp/{molecule.yml, prepare.yml, converge.yml, verify.yml}

Capstone lab + final quiz

myapp roleization + collection dependencies + Vault + error rollback + lint + Molecule + EE: deliver an automation project that is “production-ready”
After class ≈ 40 minIntegrate all modules
Scenario The platform team is taking over myapp’s automation. Review requirements: the code is organized as roles with validated interfaces; dependent collection versions are pinned; Redis must have a password, which may enter Git only as ciphertext and must never appear in logs; a failed release must roll back automatically and turn the pipeline red; you must be able to deploy config only and rehearse changes; the lint with the production profile and the Molecule idempotence test must pass; and finally it must run in an EE with results matching the local machine. Please complete this in ~/ansible-lab , and record the evidence (command output) for each step.
Structure and interfaces (Module 1): confirm the three roles and argument_specs:
cd ~/ansible-lab
ls roles/*/meta/
ansible-doc -t role -r roles myapp | head -20
ansible-playbook site.yml --syntax-check && ansible-playbook site.yml --list-tasks | grep -c "myapp :"
Pinned dependencies (Module 2): change all versions in requirements.yml to exact versions, reinstall, and record:
sed -i 's/">=14.0.0,<15.0.0"/"14.0.1"/' requirements.yml
ansible-galaxy collection install -r requirements.yml -p ./collections --force
ansible-galaxy collection list | grep -E "community.general|ansible.posix|community.docker"
Variables and secrets (Modules 3, 4): confirm there are no plaintext passwords and the final variable values match expectations:
grep -rnE "password: *['\"]?[A-Za-z0-9]{8,}" inventory/ roles/ --include=*.yml | grep -v vault_ || echo "no plaintext secrets"
head -1 inventory/group_vars/all/vault.yml
ansible-playbook show-vars.yml
no plaintext secrets
$ANSIBLE_VAULT;1.2;AES256;dev
ok: [node3] => { "msg": "node3 myapp_workers=3 (int)" }
ok: [node2] => { "msg": "node2 myapp_workers=4 (int)" }
Failure rollback drill (Module 5): release a bad version and prove automatic rollback with a non-zero exit code:
printf 'raise SystemExit("boom")\n' > roles/myapp/files/app_broken.py
ansible-playbook site.yml --limit app -e myapp_version=9.9.9-bad -e myapp_app_source=app_broken.py; echo "exit=$?"
ansible app -b -m ansible.builtin.command -a "readlink /opt/myapp/current"
rm roles/myapp/files/app_broken.py
fatal: [node2]: FAILED! => {"changed": false, "msg": "Release 9.9.9-bad failed at 'Wait for health check'; rolled back to 1.1.0"}
NO MORE HOSTS LEFT *************************************************************
node2  : ok=14  changed=5  unreachable=0  failed=1  skipped=0  rescued=1  ignored=0
exit=2
node2 | CHANGED | rc=0 >>
/opt/myapp/releases/1.1.0
node3 | CHANGED | rc=0 >>
/opt/myapp/releases/1.1.0

Because serial: 1, node2 (first batch) rolls back to 1.1.0, and node3 was not touched and remains at 1.1.0.

Minimal change and rehearsal (Module 6): change node2’s workers to 5; rehearse first, then execute, changing only configuration:
echo "myapp_workers: 5" > inventory/host_vars/node2.yml
ansible-playbook site.yml --limit node2 --tags config --check --diff
ansible-playbook site.yml --limit node2 --tags config
ansible-playbook site.yml --limit node2 --tags smoke
Quality gates (Module 7):
ansible-lint --profile production && echo LINT_OK
molecule test -s myapp && echo MOLECULE_OK
Execution environment (Module 8): run the complete playbook in the EE; it must show changed=0:
mv collections collections.local
ansible-builder build -f execution-environment.yml -t myapp-ee:1.0.0 --container-runtime docker
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/ansible_lab
ansible-navigator run site.yml -m stdout | tail -5
mv collections.local collections
Return to Module 0 and redo the production-readiness self-assessment, and compare the scores. Keep node1–node3 and ~/ansible-lab for Lesson 3 (Azure); if you need to free resources: docker rm -f node3 node2 node1,docker rmi myapp-ee:1.0.0; when the Azure VMs are idle, stop them or run az group delete -n rg-ansible-lab --yes --no-wait.
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answers)

1. What is the fundamental difference between import_role and include_role? Give one scenario that can only use each.

import is expanded at parse time (static): when/tags are copied to each child task, and the tasks inside are --list-tasks visible; include is expanded at runtime (dynamic): it can loop, can use facts/register to choose the role name, evaluates when only once, and needs apply for tags. Only include can: choose a role by ansible_facts.os_family and loop over the tenant list. import fits when you want --list-tags fully listed and want --tags tags to select inner tasks.

2. Why can the project’s ./collections “override” the collection bundled with the community package? What problem does this cause in an EE?

At runtime, lookup goes playbook-adjacent directory → collections_path → sys.path, and the first match wins. In the EE, the project directory is mounted into the container; if the project still has ./collections, it overrides the version installed in the EE, which breaks the “pinned EE version”.

3. From lowest to highest precedence, list role defaults, host_vars, group_vars/all, role vars, extra vars, play vars, set_fact, and group_vars/app.

role defaults (2) < group_vars/all (4) < group_vars/app (6) < host_vars (9) < play vars (12) < role vars (15) < set_fact (19) < extra vars (22).

4. How does Vault’s encryption mechanism determine a “wrong password”? Why does the same plaintext encrypt differently each time?

It uses PBKDF2-SHA256 (random salt, 10000 iterations) to derive the AES key and HMAC key from the password; before decrypting, it verifies HMAC-SHA256, and a mismatch means a wrong password (so the next candidate is tried). The salt is random each time, so the ciphertext differs each time.

5. Design a rolling release: one host at a time, automatic rollback on failure, and the pipeline must turn red after rollback.

play level serial: 1 + max_fail_percentage: 0; in the role, the block contains “new version directory → switch symlink → restart → health check (until/retries)”, and rescue points the symlink back to the old version, restarts, then ansible.builtin.fail re-raises, and always writes the deployment record.

6. The Molecule idempotence step failed. How do you tell whether “the test should be adjusted” or “the code has a problem”?

Look at the listed tasks: if a task should change every time (audit logs, timestamp records), add the molecule-idempotence-notest tag; if it is a configuration or installation task, the implementation is not idempotent (command without changed_when/creates, templates with content that changes every time, module parameters that rewrite on every run); fix the code rather than hiding it.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified 2026-11-15)
TopicVerification resultSources (accessed 2026-11-15)
ansible-core / community packagecore 2.21 (GA 2026-05, patch around 2.21.5, EOL 2027-11), 2.20 (EOL 2027-05), 2.19 (EOL 2026-11); community package 14.x is based on core 2.21; control node Python 3.12–3.14Releases and maintenance
core 2.19 template changesConditions must be boolean (“Conditionals must have a boolean result”,ALLOW_BROKEN_CONDITIONALS can be downgraded to a warning); template delimiters are not supported in expressions; trusted/untrusted templates; native types are the only mode; undefined values raise errors in filters and tests; omit no longer leaks; EncryptedString replaces AnsibleVaultEncryptedUnicodePorting Guide core 2.19
Variable precedence22-level list (role defaults at level 2, role vars at level 15, extra vars at level 22)Using variables
Role / import / includerole directory conventions, argument_specs, deduplication, static vs dynamic reuse comparisonRoles · Re-using artifacts
Collection versionscommunity.general 14.0.1, ansible.posix 2.2.2, community.docker 5.4.0 (Galaxy API highest_version)Ansible Galaxy
Vaultvault-id, client script naming rules, formats 1.1/1.2, PBKDF2/HMAC/AES-CTRVault guide
check mode supportansible.builtin.uri: check_mode none; ansible.builtin.command: partial (creates/removes)uri · command
Tool versions (PyPI)ansible-lint 26.11.0 (2026-11-05, Python ≥ 3.10); molecule 26.11.0 (2026-11-05, ≥ 3.11); molecule-plugins 26.11.0 (2026-11-02); ansible-navigator 26.11.0 (2026-11-05, ≥ 3.10); ansible-builder 3.2.0 (2026-10-13, ≥ 3.11)ansible-lint · molecule · molecule-plugins · navigator · builder
MoleculeDefault test sequence (dependency… idempotence… verify… destroy); the official getting-started example uses Ansible-native create/destroy (containers.podman); the docker driver comes from molecule-plugins and supports platform keys such as privileged, cgroupns_mode, volumes, and commandmolecule docs (GitHub) · molecule-plugins
ansible-builderKeys of definition file version 3 (images.base_image, dependencies.*, options.package_manager_path/tags/user, additional_build_steps); only RPM base images are supported; sample base image docker.io/redhat/ubi9:latestAnsible Builder docs
ansible-navigatorSettings file lookup order (ANSIBLE_NAVIGATOR_CONFIG → project directory → home directory); pull policies always/missing/never/tag; the default EE image could not be verified in the official docs, so this lesson specifies the image explicitlyAnsible Navigator docs
AAPAAP 2.6 is the last version supporting RPM installation; from 2.7 only containerized installationRed Hat AAP docs

Video verification notes

The following videos were verified through the YouTube oEmbed API (2026-11-15): titles, channels, and video IDs match; all are from Jeff Geerling’s “Ansible 101” livestream series (2020, English): Episode 4 “Your first real-world playbook” (SLW4LX7lbvE), Episode 5 “Playbook handlers, environment vars, and variables” (HU-dkXBCPdU), Episode 6 “Ansible Vault and Roles” (JFweg2dUvqM), Episode 7 “Molecule Testing and Linting and Ansible Galaxy” (FaXVZ60o8L8), Episode 8 “Playbook testing with Molecule and GitHub Actions CI” (CYghlf-6Opc), Episode 10 “Ansible Tower and AWX” (iKmY4jEiy_A), Episode 13 “Ansible Collections and a Test Plugin” (nyXDR4RG4A8). oEmbed does not return durations; the “about 1 hour” on the cards comes from the author’s blog description of the series. These videos were recorded in the Ansible 2.9/2.10 era; for newer content such as enforced FQCN, argument_specs, data tagging, and EEs, this lesson and the official docs take precedence. No verified dedicated videos were found for error handling, tags/check, or EE/navigator, so storyboards are provided instead.

Narration notes

The “Audio” page uses the browser’s built-in Web Speech API (speechSynthesis, en-US) to read the script aloud in real time; English terms are pronounced with en-US; the result depends on the voices installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, pass the script to a TTS service such as Azure AI Speech.

Known limitations

  • The commands in this courseware were not actually executed in the generation environment; the patch version numbers, times, IPs, hashes, counts, and image IDs in the “expected output” are sample values, and the actual values in your environment take precedence. The log wording of the tools (ansible-lint, Molecule, navigator) changes with versions.
  • The lab environment matches Lesson 1: Docker network anslab (172.30.0.0/24), node1 172.30.0.11 (lb + cache: nginx + Redis), node2 172.30.0.12 and node3 172.30.0.13 (app: myapp, port 5000), SSH directly to port 22 via container IPs. This lesson renames Lesson 1’s variables with the myapp_* prefix, and wraps the Redis tasks into a redis role applied to the cache group.
  • Managed nodes and Molecule instances are both privileged containers with systemd as PID 1, which differ from VMs (kernel parameters, firewalls, cgroups); production roles should add VM testing.
  • Molecule can be written in two ways (the molecule-plugins docker driver / the Ansible-native default driver); this lesson uses the former; molecule init scenario the generated files follow the installed version.
  • For the UBI9 Python 3.12 package name in execution-environment.yml and the ansible-navigator setting keys, follow the ansible-builder docs and ansible-navigator settings --sample as authoritative; the navigator default EE image could not be verified.
  • External secret lookup plugin names (azure_keyvault_secret, vault_kv2_get, secretsmanager_secret) should follow each collection’s current docs; Lessons 3 and 4 verify them in detail.
  • The steps and counts in the animations are illustrative, used to explain the mechanisms.