Ansible Lesson 2: From “It Works” to “Production-Ready”
- Use
ansible-galaxy role initto split the playbook into role, clearly explain the difference betweendefaults/andvars/, as well asmeta/main.ymldependencies andmeta/argument_specs.ymlargument validation, and choose betweenimport_role(static) andinclude_role(dynamic) based on the scenario. - Use FQCN to reference modules, use
requirements.ymlto pin collection versions and install them into the project’scollections/, 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-idto separate dev/prod passwords, together withno_logto 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_fatalto write tasks where failures can be rolled back and results are trustworthy; use tags,--check --diffto 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
| # | Time | Module | Core content | Animation / interaction | Lab (node1–node3) |
|---|---|---|---|---|---|
| 0 | Before class | Transition and warm-up | Check the Lesson 1 control node, the 3 managed nodes, and myapp; rebuild in one step if anything is missing | 8-item self-assessment of “production readiness” | ansible all -m ping All green |
| 1 | 00–08 | Role structure and reuse | role directory conventions, defaults vs vars, handlers, meta dependencies and argument_specs, roles: / import_role / include_role, static vs dynamic | Static import vs dynamic include: parse-time vs runtime comparison | Split myapp into three roles: common / redis / myapp |
| 2 | 08–14 | Collections and ansible-galaxy | FQCN, collection search path, requirements.yml, version ranges and pinning, offline tarballs, verify | FQCN resolution and collection installation flow | Install community.general / ansible.posix within the project |
| 3 | 14–21 | Variable precedence and organization | 22 precedence levels, the 8 most common, group_vars/host_vars directories, extra vars, naming conventions, stricter templating and conditionals from 2.19 onward | Core animation: same-named variable overridden layer by layer to reach the final value | Same variable defined at 5 levels, verified with debug |
| 4 | 21–28 | Ansible Vault and secrets | encrypt / encrypt_string / rekey, vault-id labels, password files and client scripts, no_log, vault_ indirect variables, external secret management | Vault decryption flow (vault-id match → PBKDF2 → HMAC → AES) | Encrypt the Redis password, with separate dev/prod passwords |
| 5 | 28–35 | Error handling | block / rescue / always, ignore_errors, failed_when, changed_when, any_errors_fatal, max_fail_percentage | Multi-host failure handling simulator | Automatic rollback to the previous version when a release fails |
| 6 | 35–41 | Tags, check, and diff | --tags / --skip-tags, always / never, tag inheritance for import vs include, check_mode compatibility, --diff | Tag filter: which tasks will run | Push configuration only, dry-run changes |
| 7 | 41–51 | ansible-lint and Molecule | lint rules and profiles, .ansible-lint, Molecule scenarios, Docker containers, converge → idempotence → verify | Molecule test sequence (including an idempotence failure) | Add lint + Molecule to the myapp role |
| 8 | 51–60 | Execution environments and ansible-navigator | Why EEs are needed, execution-environment.yml v3, ansible-builder build stages, navigator run / settings / artifact | EE build and run flow + troubleshooting tree | Build myapp-ee and deploy with navigator |
| — | After class | Cheat sheet · Capstone lab | myapp roleization + Vault + lint + Molecule + EE, end to end | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Refactor the playbook into reusable roles | ✓ | · | ✓ | · | · | · | ✓ | · | ansible-galaxy role init | Three myapp roles |
| Choosing static vs dynamic reuse | ✓ | · | · | · | · | ✓ | · | · | import_role / include_role | M1, M6 labs |
| Manage collection dependencies and versions | · | ✓ | · | · | · | · | ✓ | ✓ | ansible-galaxy collection install -r | requirements.yml |
| Predict final variable values and avoid conflicts | ✓ | · | ✓ | ✓ | · | · | · | · | ansible-inventory --host,debug | 5-level override lab |
| Encrypt and use secrets | · | · | ✓ | ✓ | · | · | · | ✓ | ansible-vault encrypt_string --vault-id | Redis password |
| Failure handling and rollback | · | · | · | · | ✓ | · | ✓ | · | block/rescue/always | Failure rollback |
| Safe partial execution and dry runs | · | · | · | · | · | ✓ | · | · | --tags,--check --diff | Push config only |
| Static checks and automated testing | · | · | · | · | ✓ | · | ✓ | · | ansible-lint,molecule test | Molecule scenarios |
| Portable runtime environment | · | ✓ | · | · | · | · | · | ✓ | ansible-builder build,ansible-navigator run | myapp-ee |
Out-of-scope topics (and where to learn them)
| Topic | Why not covered here | Where to learn |
|---|---|---|
| Azure Key Vault lookups, managed identities | Requires cloud resources; this lesson only covers the trade-offs between Vault and external secrets | Lesson 3 Module 5 |
| AWS Secrets Manager / SSM Parameter Store lookup | Belongs to the AWS topic | Lesson 4 |
| Running lint/Molecule in CI, using EEs in AWX/AAP, Event-Driven Ansible | Belongs to automated ops pipelines | Lesson 5 |
| Writing custom modules and plugins, publishing your own collection to Galaxy / Automation Hub | Aimed at content developers; exceeds 1 hour | Lesson 7;Developing collections |
| Performance tuning (forks, pipelining, strategy, mitogen) | Belongs to deep troubleshooting and optimization | Lesson 7 |
How to use this courseware
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.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).
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.
{{ }}, 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)
- 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-labcontainsansible.cfg,inventory/hosts.ini, group_vars/host_vars, and the Lesson 1 Module 8site.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 throughhttp://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.
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
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.
Module 1 · Role structure and reuse
- 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) fromvars/(high precedence, role-internal constants), and usemeta/argument_specs.ymlto make wrong arguments fail before the first task. - Be able to choose as needed among
roles:,import_role, andinclude_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.”
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.
| Directory | Contents | When loaded | Typical use |
|---|---|---|---|
tasks/main.yml | Task list (entry point) | When the role runs | Can be further split with import_tasks / include_tasks into sub-files; tasks_from: can select other entry points via |
handlers/main.yml | Handlers | When the role is added to a play | Restart services; handlers are visible across the whole play |
defaults/main.yml | Default variables | When the role is added to a play | Lowest precedence (level 2 of the 22), reserved for users to override |
vars/main.yml | Role variables | When the role is added to a play | High precedence (level 15); for OS package names, internal paths, and other constants that should not be overridden by inventory |
templates/,files/ | Jinja2 templates, static files | Referenced by the template/copy modules | src: app.py Automatically searched for in the role’s files/ directory |
meta/main.yml | galaxy_info,dependenciesallow_duplicates | When the role is added to a play | Declares dependent roles (run before this role) |
meta/argument_specs.yml | Argument spec | Automatically inserts a validation task when the role runs | Type, required, and allowed-value checks; generates documentation |
library/,module_utils/,*_plugins/ | Modules and plugins embedded in the role | Added to the search path when the role is used | New 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:
| Method | Static / dynamic | Location | Characteristics |
|---|---|---|---|
roles: Keyword | Static | Play level | Classic syntax; execution order: pre_tasks → handlers → roles → tasks → handlers → post_tasks → handlers |
ansible.builtin.import_role | Static (expanded at parse time) | Task level | Can 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_role | Dynamic (expanded at runtime) | Task level | Can 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:orimport_role(static, predictable,--list-tasks/--list-tagscan be fully listed). - For loops, or for choosing roles based on runtime facts (e.g., by
ansible_facts.os_familyincluding 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.ymlthedependenciesmeta 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 role | Terraform module | Helm chart | Chef cookbook / Puppet module | |
|---|---|---|---|---|
| Interface | defaults + argument_specs | variable / output | values.yaml + values.schema.json | attributes / class parameters |
| Dependencies | meta dependencies, collections | module source + version | Chart.yaml dependencies | metadata.rb depends |
| Distribution | Galaxy / Automation Hub (mostly within collections) | Registry | OCI / chart repo | Supermarket / Forge |
| Testing | Molecule | terraform test | helm test / chart-testing | Test Kitchen / rspec-puppet |
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
Flowchart: execution order of roles within a play
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-galaxy role init NAME | Create a role from the standard skeleton | --init-path roles Specify the parent directory; --role-skeleton DIR Use a team-custom skeleton |
ansible-galaxy role list | List roles findable in roles_path | -p roles Specify a path |
ansible-doc -t role -l / ansible-doc -t role NAME | List roles and view the documentation generated from argument_specs | -r roles Specify the role search directory |
ansible-playbook site.yml --list-tasks | Does not execute; lists the expanded tasks | Statically imported tasks are visible; dynamically included ones only show the include itself |
ansible-playbook site.yml --syntax-check | Syntax check | Catches role names that cannot be found and YAML errors |
ansible localhost -m ansible.builtin.validate_argument_spec | Calls 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)
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_ ):
--- # 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
--- - 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).
---
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_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”.
---
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.
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.
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: configOr use the tags already set up in the lab: ansible-playbook site.yml --tags config (Module 6).
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
Official docs
- Roles
- Re-using Ansible artifacts (import vs include comparison table)
- include_role module · import_role module
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.
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.
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.
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.
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.
Module 2 · Collections and ansible-galaxy
- Explain collection naming (
namespace.collection) and FQCN (namespace.collection.plugin), and know that ansible-core ships onlyansible.builtin, while the community packageansible14.x preinstalls about a hundred collections. - Write a
requirements.ymlwith version constraints, install collections into the project./collections, and useansible-galaxy collection listto determine which version is actually loaded. - Understand offline installation (download → tarball), signature and integrity verification (verify), and private Automation Hub configuration.
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).
| Term | Example | Description |
|---|---|---|
| namespace | community,ansible,azure,amazon | publisher namespace |
| collection | community.general,ansible.posix | distribution and versioning unit (semantic versioning) |
| FQCN | community.general.timezone | Fully Qualified Collection Name: namespace.collection.plugin_name |
ansible.builtin | ansible.builtin.copy | Shipped with ansible-core; its version is the core version |
ansible.legacy | Short 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
timezonemay 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
ansibleupgrades 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 projectrequirements.yml+./collectionskeeps 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
- playbook-adjacent directory:
<playbook directory>/collections/ansible_collections/(highest precedence; suitable for project-pinned versions). collections_pathConfiguration (ansible.cfg[defaults] collections_path, environment variableANSIBLE_COLLECTIONS_PATH), default~/.ansible/collections:/usr/share/ansible/collections.- Python
sys.pathin theansible_collectionspackage (collections_scan_sys_path, enabled by default): the community package installed via pip/pipxansibleplaces 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
| Format | Meaning | Use case |
|---|---|---|
"2.2.2" or "==2.2.2" | exact version | production, EE builds (recommended) |
">=14.0.0,<15.0.0" | latest within the same major version | development environments; combine with periodic upgrades |
"*" (default) | Any latest version | Only suitable for experiments |
"!=14.0.0" | Exclude a problematic version | Temporary 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
ansiblewith 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 downloadProduce a tarball + requirements.yml, copy them into the internal network, theninstall --offline, or set up a Private Automation Hub.
Comparison with similar technologies
| Ansible collection | Terraform provider | Python packages | |
|---|---|---|---|
| Dependency declaration | requirements.yml | required_providers | requirements.txt / pyproject |
| Lock file | No native lock file (exact versions or EE) | .terraform.lock.hcl | pip-tools / uv.lock |
| Install location | Project collections/ or user directory | .terraform/providers | venv site-packages |
| Integrity | SHA256 + optional GPG signature (verify) | Hash + signature | Hash (--require-hashes) |
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
Flowchart: how a task’s module name is resolved
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-galaxy collection install -r requirements.yml -p ./collections | Install into the project directory from a file | -U/--upgrade upgrade; --force reinstall; --no-deps; --pre allow pre-releases; --offline |
ansible-galaxy install -r requirements.yml | install both at the same time roles: and collections: two parts | roles are installed into the first entry of roles_path, collections into the first entry of collections_path |
ansible-galaxy collection list | List the installed collections and their versions in each path | Can filter by name: list community.general; --format json |
ansible-galaxy collection download -r requirements.yml -p ./offline | Download tarballs for offline installation | also generates offline/requirements.yml |
ansible-galaxy collection verify NAME | Compare local files against server checksums | --offline Use the local MANIFEST only; --signature,--keyring |
ansible-doc community.general.timezone | View module documentation and examples | -l community.general List the modules in this collection |
ansible-config dump | grep -i collection | View 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)
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"
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
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).
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.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.
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
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
Official docs
Video storyboard (about 75 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Module 3 · Variable precedence and organization
- 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.
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.
| # | Source | Description / typical use |
|---|---|---|
| 1 | Command-line options (such as -u my_user) | These are not variables; they are connection parameters, with the lowest precedence |
| 2 | role defaults (roles/x/defaults/main.yml) | The role’s “factory defaults”,the easiest to override |
| 3 | Group variables in an inventory file or script | hosts.ini in [group:vars] section |
| 4 | inventory group_vars/all | Global defaults (environment level) |
| 5 | playbook group_vars/all | group_vars/all in the directory next to the playbook |
| 6 | inventory group_vars/* | Per group (app, redis, prod, …) |
| 7 | playbook group_vars/* | |
| 8 | Host variables in an inventory file or script | hosts.ini on the host line, ansible_host=… , etc. |
| 9 | inventory host_vars/* | Exceptions for a single host |
| 10 | playbook host_vars/* | |
| 11 | Host facts / cached set_fact | ansible_facts.* (injected ansible_* variables) |
| 12 | play vars | The play’s vars: |
| 13 | play vars_prompt | |
| 14 | play vars_files | |
| 15 | role vars (roles/x/vars/main.yml) | Role-internal constants —override inventory! |
| 16 | block vars | Only applies to tasks inside the block |
| 17 | task vars | Only applies to that task |
| 18 | include_vars | Variable files loaded at runtime |
| 19 | set_fact / register | Values computed at runtime |
| 20 | role (and include_role) parameters | Parameters passed when calling a role |
| 21 | include parameters | include_tasks and other passed parameters |
| 22 | extra 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 (
allis the parent of all groups, so group_vars/app overrides group_vars/all). - Sibling groups: A host belongs to both
appandcanary, 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 variableansible_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 underinventory/, 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 tomergeis 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=4Values 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):
| Change | Before | Now (2.19+, including 2.21) | How to fix |
|---|---|---|---|
| Conditions must be booleans | when: 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 expressions | when: "{{ x }} == 1",failed_when: 1 + {{ value }} == 2 | Error “Template delimiters are not supported in expressions”; a template inside a template is no longer evaluated a second time | Write the variable name directly: when: x == 1 |
| Trusted templates | any {{ }} 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 types | Result strings were “guessed” into Python literals | Jinja native mode is the only mode; the final literal evaluation was removed | Convert explicitly when a type is needed: | int,| bool,| from_json |
| Undefined values | Some filters/tests silently accept undefined values | Undefined values raise errors in filters and tests | Use | default(...) or is defined |
| omit leakage | omit inside a loop item affects task parameters | No longer leaks | Write {{ item.x | default(omit) }} |
When: which layer variables go in (recommended organization conventions)
| Layer | What goes here | Example |
|---|---|---|
| role defaults | All tunable parameters and their safe defaults (documented) | myapp_port: 5000 |
| role vars | Constants tied to the OS or implementation that users should not change | myapp_packages,myapp_unit_file |
| group_vars/all | Environment-level settings: timezone, NTP, monitoring addresses, domain names | common_timezone |
| group_vars/<functional group> | Parameters for that group’s services | group_vars/app.yml: myapp_workers: 4 |
| group_vars/<environment group> | dev/prod differences (or one inventory directory per environment) | inventories/prod/group_vars/… |
| host_vars | True single-host exceptions (keep to a minimum) | a large-memory machine’s myapp_workers: 8 |
| extra vars | One-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
| Ansible | Terraform | Helm | |
|---|---|---|---|
| Layers | 22 levels, by source | default → tfvars → *.auto.tfvars → -var (later wins) | chart values → -f files (later wins) → --set |
| Dictionary merging | Replaced by default (merge with combine) | No merging (replaced as a whole) | Deep merge |
| Highest precedence | extra vars (-e) | -var / -var-file (command-line order) | --set |
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
Flowchart: how variables “stack up” within a play
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-inventory --host node3 | Variables for the host after merging at the inventory layers (levels 3–10) | --yaml; --vars --graph View the group tree and variables |
ansible-inventory --graph --vars | Group hierarchy + variables at each layer | Troubleshoot parent/child group overrides |
ansible node3 -m ansible.builtin.debug -a var=myapp_workers | Ad-hoc view (excludes role and play layers) | Can only see inventory + extra vars |
ansible.builtin.debug: var=… (within a play) | View the final value | Tasks placed inside a role or after one |
-e key=value / -e '{"k": 4}' / -e @file.yml | extra vars | key=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)
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).
---
- 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.
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.”
- 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.
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.
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}'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
Official docs
- Understanding variable precedence
- Organizing host and group variables
- ansible-core 2.19 Porting Guide (data tagging)
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Module 4 · Ansible Vault and secrets
- 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@sourceto manage multiple dev/prod passwords; the source can be a prompt, a file, or a client script. - Use
vault_indirect variables,no_log,diff: falseto 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.
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.
| Form | Command | Ciphertext appearance | Use case |
|---|---|---|---|
| Encrypt an entire file | ansible-vault encrypt vault.yml / create / edit | first line of the file $ANSIBLE_VAULT;1.1;AES256 | Secrets stored centrally in group_vars; files such as certificate private keys (the copy module decrypts them automatically src) |
| Encrypt a single value | ansible-vault encrypt_string | key: !vault | + multi-line ciphertext | Mix 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
- Header:
$ANSIBLE_VAULT;1.1;AES256(no label) or$ANSIBLE_VAULT;1.2;AES256;prod(format 1.2, with a vault-id label). - 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.
- 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.
- Encoding: salt, HMAC, and ciphertext are each hex-encoded, joined with newlines, then hex-encoded again as a whole, and wrapped at 80 columns.
- vault-id:
--vault-id label@source. The source can beprompt(interactive input), a password file path, or executable script (which prints the password to stdout; “client scripts” whose filenames end in-clientor-client.extensionalso receive the--vault-id labelargument, so one script can serve multiple labels). You can provide several--vault-id. - 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. - From 2.19: After decryption, the value is internally a string with an “encryption source” tag (
EncryptedStringreplaces the oldAnsibleVaultEncryptedUnicode), which is transparent to playbook authors; in custom plugins, checks for the old typeisinstanceneed to be updated.
Leak prevention: Vault only protects secrets at rest
| Leak path | Protection |
|---|---|
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 rendering | On the task, use diff: false (or no_log) |
| Items in loop output | loop_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 output | Also depends on no_log; do not use ANSIBLE_DEBUG=1 in production runs. |
When: Vault or external secret management
| Ansible Vault | External secret management (Azure Key Vault, HashiCorp Vault, AWS Secrets Manager, CyberArk) | |
|---|---|---|
| Onboarding effort | Zero dependencies, built into ansible-core | Requires a service, network, and identity (managed identity / OIDC / AppRole) |
| Rotation | Manual rekey and redeploy; rotating a value means editing and committing the file | Server-side rotation; the playbook looks up the latest value on each run |
| Auditing | Git 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 Ansible | vault.yml in group_vars / !vault | lookup 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 |
| Recommended | Small 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) |
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
Flowchart: structure of vault ciphertext
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-vault create FILE | Create a new encrypted file (opens $EDITOR) | --vault-id dev@prompt |
ansible-vault edit FILE | Decrypts to a temp file for editing; re-encrypts on save | Plaintext does not land in the working directory |
ansible-vault view FILE | View 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_string | Encrypt 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@SRC | Provide the password at runtime | can be repeated; --ask-vault-pass ≈ --vault-id @prompt; --vault-password-file |
| ansible.cfg | Default vault password source | vault_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)
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
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)"
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.
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”.
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.
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).
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
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
Official docs
- Protecting sensitive data with Ansible vault
- Managing vault passwords (vault-id, client scripts)
- Logging Ansible output (no_log)
Video storyboard (about 80 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Module 5 · Error handling: block, rescue, failed_when
- 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 / alwaysto implement “automatic rollback on deployment failure”, usingansible_failed_task,ansible_failed_resultin rescue. - Be able to use
failed_when,changed_whento correct module judgments of “success / changed”; know the limits ofignore_errors; and useany_errors_fatal,serial+max_fail_percentageto control the “blast radius” of failures.
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).
| Keyword | Purpose | Notes |
|---|---|---|
block | Groups multiple tasks together, sharing attributes such as when / become / tags / vars | block itself is not a loop and cannot loop |
rescue | Runs 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 |
always | Runs whether the tasks succeed or fail (like finally) | Suitable for cleaning up temp files, writing audit records, sending notifications |
ignore_errors: true | Continue running subsequent tasks after a task fails | counted as ignored in RECAP; cannot ignore unreachable (use ignore_unreachable), undefined variables, or syntax errors |
failed_when | Custom failure conditions | A list means “fail only if all are true” (AND); failed_when: false never fails |
changed_when | Custom “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: true | If any host fails, all hosts stop the play after the current task finishes | Suitable for changes where “the cluster must be consistent” (database primary/replica, config distribution) |
serial + max_fail_percentage | Runs in batches; stops subsequent batches once the failure ratio is exceeded | The core of rolling releases; also stops if an entire batch fails |
until / retries / delay | Retry until the condition is met | Health 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:
grepnot found returns 1 (not necessarily an error), and some scripts still return 0 when they fail. command/shellAlways 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
- 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.
- 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.failexplicitly “re-raise”), the host fails. - always always runs after block/rescue (even if rescue fails).
failed_when/changed_whenEvaluated on the control node after the module returns; can referenceregisterresults; ansible-core 2.19+ requires the result to be a boolean.any_errors_fatalSet 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
| Scenario | Recommended |
|---|---|
| Release failure needs rollback | block (release + health check) / rescue (rollback + fail to re-raise) / always (record) |
| Command return code does not represent success or failure | register + failed_when |
| Read-only query commands | changed_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 consistent | any_errors_fatal: true |
| Rolling releases to control the blast radius | serial: [1, "30%"] + max_fail_percentage: 0 |
Comparison with similar technologies
| Ansible | Bash | Terraform | |
|---|---|---|---|
| try/catch | block / rescue / always | set -e + trap | None (after a failure, state is partially written; fix it on the next plan) |
| Custom failure | failed_when | || exit 1 | precondition / postcondition |
| Parallel failure control | any_errors_fatal, serial, max_fail_percentage | Manual | -parallelism, no concept of batches |
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
Flowchart: comparison of multi-host failure strategies
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
| Syntax | Purpose | Notes |
|---|---|---|
block / rescue / always | Transactional task group | Nestable; block-level when applies to each task inside |
ansible_failed_task / ansible_failed_result | get the failed task and its results in rescue | ansible_failed_task.name,ansible_failed_result.msg |
failed_when: … | Custom failure | list = AND; for OR, write it in one expression |
changed_when: … | Custom change | use for read-only commands false |
until / retries / delay | Retry | default retries 3, delay 5 (per the docs) |
any_errors_fatal / max_fail_percentage / serial | Play-level failure strategy | See the principles table |
--force-handlers | Failed hosts still run notified handlers | or play-level force_handlers: true |
--start-at-task "NAME" / --step | Start from a certain task / confirm each task one by one | After 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)
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.
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
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=0ansible 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
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.
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.
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
- Error handling in playbooks
- Blocks
- Controlling playbook execution: strategies and more (serial, max_fail_percentage)
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Module 6 · Tags, check, and diff modes
- Be able to use
--tags/--skip-tags/--list-tags, understand the special tagsalways,neverandtagged,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 --diffto rehearse changes, know which modules do not support check mode (they get skipped), and how to usecheck_mode,ansible_check_modeso the playbook also runs through in check mode.
What: what tags, check, and diff each are
| Feature | Command line | Purpose |
|---|---|---|
| Tags | --tags config,--skip-tags install | select tasks to run or skip by tag |
| Check mode (dry run) | --check / -C | Modules that support check only predict whether they would change, without modifying the target; unsupported modules are skipped |
| Diff mode | --diff / -D | Modules that support diff (template, copy, lineinfile, file, etc.) show before/after differences; can be combined with check |
Special tags
| Tag | Behavior |
|---|---|
always | Always runs regardless of --tags what is selected, unless --skip-tags always. gather_facts and the role argument validation task carry this tag by default |
never | Not 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 / all | Run 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 configfinishes in one minute, with a smaller change surface. - Change review:
--check --diffoutput 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 > 0indicates 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, useapply: { tags: [...] }, or tag each inner task individually. - Selection logic: The effective tag set of a task and
--tagsintersect (or it contains always) → selected; then, if it intersects--skip-tags, it is skipped.--list-tasks --tags XIt can be previewed. - check mode: The control node passes
_ansible_check_mode=Truealong with the module parameters to the remote side; the module decides for itself and returnschangedpredictions; in the module doc’s Attributes table,check_modeis full / partial / none. For example,ansible.builtin.uriis none (skipped in check mode), andansible.builtin.commandis partial (it only predicts when used withcreates/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 variableansible_check_modeindicates whether check mode is currently active. - diff: The module returns
difffields (before/after), and the callback handles display; at the task level,diff: falseturns 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
neverplus a specific tag. - Use
--check --diffas 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 getcheck_mode: false+changed_when: false.
Comparison with similar technologies
| Ansible --check --diff | terraform plan | kubectl diff / --dry-run=server | |
|---|---|---|---|
| Accuracy | Depends on each module’s implementation; dependency chains can “break” | Provider-based plan, more complete | Validated on the API server side, more complete |
| When unsupported | Task is skipped (may hide subsequent changes) | (known after apply) | — |
| Can save the execution | No (recalculated on the next run) | Yes -out (save plan) | No |
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
Flowchart: the fate of a task in check mode
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
| Command | Purpose | Notes |
|---|---|---|
ansible-playbook site.yml --list-tags | List all tags | Shows only statically visible tags (cannot see inside includes) |
--list-tasks --tags config | Preview the selected tasks | Does not connect to hosts |
--tags a,b / --skip-tags c | Select / exclude | Can be specified multiple times |
--check / -C | Dry run | Unsupported modules are skipped |
--diff / -D | Show differences | Most commonly used in combination with -C |
--limit node3 | Limit hosts | Combined 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)
cd ~/ansible-lab ansible-playbook site.yml --list-tags ansible-playbook site.yml --list-tasks --tags config
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.
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.
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.
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.
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
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.
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.
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.
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.
Module 7 · ansible-lint and Molecule testing
- Be able to run ansible-lint and read its output, understand the profiles (min → basic → moderate → safety → shared → production), and
.ansible-lintconfiguration; be able to use--fixfor automatic fixes, and# noqaandskip_listto 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.
What: two kinds of tools
| ansible-lint | Molecule | |
|---|---|---|
| Type | Static analysis (does not connect to hosts) | Integration test (actually executes) |
| What it finds | Non-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 |
| Speed | Seconds | Minutes (creating containers, installing software) |
| Where it runs | pre-commit + CI on every commit | CI 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 rules | Meaning | Example fix |
|---|---|---|
fqcn[action-core] | Built-in module used with a short name | apt → ansible.builtin.apt |
name[missing] / name[casing] | Task has no name / name is not capitalized | Add it - name: Install packages |
no-free-form | Used key=value syntax | Change to YAML dictionary parameters |
no-changed-when | command/shell without changed_when | Add changed_when or switch to creates/removes |
risky-file-permissions | File created without setting mode | mode: "0644" |
var-naming[no-role-prefix] | Role variable not prefixed with the role name | app_port → myapp_port |
yaml[truthy] | Used yes/no | Change to true/false |
schema[meta] / schema[playbook] | File does not conform to the JSON schema | Fix the fields in meta/main.yml |
ignore-errors | Used ignore_errors | Change to failed_when (Module 5) |
command-instead-of-module | Calling systemctl/apt etc. via command | Switch 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):
| Step | What it does |
|---|---|
| dependency | Install collections/roles per requirements.yml |
| cleanup / destroy | Clean up instances left over from last time |
| syntax | ansible-playbook --syntax-check converge.yml |
| create | Driver creates instances (docker driver: pull images, start containers) |
| prepare | Test prerequisites (such as installing Redis dependencies) |
| converge | Run converge.yml (the role under test) |
| idempotence | Run converge again; fail if any task reports changed; tasks with the molecule-idempotence-notest tag are excluded |
| side_effect | Optional: simulate failure/upgrade |
| verify | Run verify.yml (default Ansible verifier; testinfra is also supported) |
| cleanup / destroy | Remove 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 convergeiterate repeatedly, and finallymolecule 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 + Molecule | Terraform | Chef | |
|---|---|---|---|
| Static checks | ansible-lint | tflint, terraform validate | Cookstyle |
| Integration tests | Molecule | terraform test, Terratest | Test Kitchen + InSpec |
| Idempotence tests | Built-in idempotence step | plan shows no changes | kitchen converge twice |
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
Flowchart: quality gates (local → CI)
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-lint | Lint the current project (auto-detects playbooks, roles, and vars files) | --profile production; -f pep8|sarif|codeclimate; --offline does not install dependencies |
ansible-lint --fix | Auto-fix fixable rules (FQCN, YAML formatting, no-free-form, etc.) | Review the git diff after fixing |
ansible-lint -L / -T | List rules / tags | |
molecule init scenario NAME | Generate a scenario skeleton | Generated files follow the installed version; this lesson gives the complete files directly |
molecule test -s myapp | Full test sequence | --destroy never Keep instances after a failure for troubleshooting |
molecule converge / idempotence / verify | Run a single step | converge is the most commonly used during development |
molecule login -s myapp | Enter the instance shell | With multiple instances, -h instance-name |
molecule list / destroy | View / 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)
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.
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.
---
- 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'roles/myapp/tasks/release.yml , add the tag to the always task:
always:
- name: Record deployment attempt
ansible.builtin.lineinfile:
…
tags: [molecule-idempotence-notest]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.
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.
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
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
Official docs
- Ansible Lint docs(rules, profiles, configuration)
- Molecule docs
- molecule-plugins (docker driver)
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Module 8 · Execution environments and ansible-navigator
- 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 runto run myapp’s site.yml in an EE; configureansible-navigator.yml(image, pull policy, network, mounts, environment variables, playbook artifact) and troubleshoot common problems.
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:
| Tool | Purpose | Version as of 2026-11 |
|---|---|---|
| ansible-builder | Reads execution-environment.yml, generates the build context (Containerfile) and calls podman/docker to build the EE | 3.2.0 (2026-10-13, requires Python ≥ 3.11) |
| ansible-navigator | Runs playbooks in the EE container (run), browses collections/docs/inventory, and replays artifacts; has a TUI (interactive) mode and a stdout mode | 26.11.0 (2026-11-05) |
| ansible-runner | The entry point inside the EE; AWX/AAP also run jobs through it | Installed inside the EE |
| AWX / AAP 2.6 | Uses 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
ansible-builder create: validates the definition file and, undercontext/, generatesContainerfileand_build/(copies requirements.yml, requirements.txt, bindep.txt, and helper scripts).- base stage: starts from
base_image, installspython_interpreter(system packages), plus ansible-core and ansible-runner (via pip). - galaxy stage:
ansible-galaxy collection install -r requirements.ymlinstalls collections (the build needs access to Galaxy / a private Hub). - 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.
- final stage: copies from base, installs system packages and wheels, copies the collections, and sets up the user (default UID 1000) and the entrypoint.
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
- Reads settings (command line > environment variables
ANSIBLE_NAVIGATOR_*> settings file:ANSIBLE_NAVIGATOR_CONFIGansible-navigator.yml, project directoryansible-navigator.yml,~/.ansible-navigator.yml), useansible-navigator settings --effectiveto view the final values. - Prepare the image according to the pull policy (
always / missing / never / tag). - Start the container: (the project directory) is mounted at the same path as the working directory; if
SSH_AUTH_SOCKexists, mount the ssh-agent socket, plus your configured volume-mounts, environment variables, and container options (such as--network=anslab). - 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 canansible-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 + navigator | pipx venv | Write your own Dockerfile to install ansible | |
|---|---|---|---|
| Dependency resolution | Automatically aggregates the Python/system dependencies declared by collections | Manual | Manual |
| AWX/AAP compatibility | Native | Not applicable | Must follow EE conventions (runner, user, entrypoint) |
| Usage experience | navigator handles mounts, agent, and artifacts | Most direct | You must write the docker run parameters yourself |
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
Flowchart: runtime of ansible-navigator run
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
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-builder create | Generate only the build context context/ | -f execution-environment.yml,-c context |
ansible-builder build -t IMG | Generate the context and build the image | --container-runtime docker; -v 3 verbose output; --build-arg; --no-cache |
ansible-navigator run PLAYBOOK | Run 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 -- CMD | Run arbitrary commands in the EE | exec -- ansible --version,exec -- ansible-galaxy collection list |
ansible-navigator images / collections / doc / inventory | Browse EE contents | TUI by default; add -m stdout for text output |
ansible-navigator settings --effective | Show the final effective settings and their sources | Troubleshoot whether the settings file is being read |
ansible-navigator replay FILE.json | Replay a playbook artifact | Post-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)
cd ~/ansible-lab ansible-builder build -f execution-environment.yml -t myapp-ee:1.0.0 --container-runtime docker -v 3 echo "context/" >> .gitignore
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.
./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
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.
ls artifacts/ ansible-navigator replay artifacts/site-artifact-*.json -m stdout | tail -5
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.
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
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
- Getting started with Execution Environments
- Ansible Builder docs(definition file version 3)
- Ansible Navigator docs
- ansible-builder on PyPI · ansible-navigator on PyPI
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly; a storyboard and narration script are provided.
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.
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.
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.
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.
Command cheat sheet
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: 0Tags / 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
| Symptom | Check first | Common causes |
|---|---|---|
| the role 'x' was not found | ansible-galaxy role list -p roles | roles_path, spelling, running from another directory |
| couldn't resolve module/action | ansible-galaxy collection list | Short names, collection not installed, path not in collections_path |
| Changed variable has no effect | debug inside the play,grep -rn | role vars / set_fact / -e overrides; dictionaries replaced as a whole |
| Conditionals must have a boolean result | Check the conditional expression | 2.19+ strict conditionals: add | bool / | length > 0 |
| no vault secrets found / Decryption failed | head -1 vault.yml Check the tags | No password provided, wrong password, vault_id_match label mismatch |
| CI shows success after rescue | Check RECAP rescued | Missing fail at the end of rescue |
| Tasks inside an include not run after --tags | --list-tasks | include does not inherit tags; apply is needed |
| Idempotence test failed | Check the listed tasks | command without changed_when, template with timestamps, audit task without notest |
| systemd does not work in Molecule | docker exec … ps -p 1 | Image / privileged / cgroup mount |
| UNREACHABLE in navigator | settings --effective | Missing --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
~/ansible-lab , and record the evidence (command output) for each step.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 :"
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"
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)" }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.
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
ansible-lint --profile production && echo LINT_OK molecule test -s myapp && echo MOLECULE_OK
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
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.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
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| ansible-core / community package | core 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.14 | Releases and maintenance |
| core 2.19 template changes | Conditions 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 AnsibleVaultEncryptedUnicode | Porting Guide core 2.19 |
| Variable precedence | 22-level list (role defaults at level 2, role vars at level 15, extra vars at level 22) | Using variables |
| Role / import / include | role directory conventions, argument_specs, deduplication, static vs dynamic reuse comparison | Roles · Re-using artifacts |
| Collection versions | community.general 14.0.1, ansible.posix 2.2.2, community.docker 5.4.0 (Galaxy API highest_version) | Ansible Galaxy |
| Vault | vault-id, client script naming rules, formats 1.1/1.2, PBKDF2/HMAC/AES-CTR | Vault guide |
| check mode support | ansible.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 |
| Molecule | Default 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 command | molecule docs (GitHub) · molecule-plugins |
| ansible-builder | Keys 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:latest | Ansible Builder docs |
| ansible-navigator | Settings 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 explicitly | Ansible Navigator docs |
| AAP | AAP 2.6 is the last version supporting RPM installation; from 2.7 only containerized installation | Red 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 themyapp_*prefix, and wraps the Redis tasks into aredisrole applied to thecachegroup. - 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 scenariothe 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-builderdocs andansible-navigator settings --sampleas 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.