Scene: running in the terminal ansible all -m ping, one host shows red UNREACHABLE. Narration: “UNREACHABLE means the connection plugin failed and the module was not transferred yet, so check the network and SSH first, not the playbook.”
Ansible Hour 8 (Optional): 50 Production Issues + 50 Interview Questions
- When you see a raw error message (
UNREACHABLE!,Missing sudo password,is undefined,couldn't resolve module/action…), you can work out which area it falls under: connection/authentication/privilege escalation, Playbook/variables/templates, modules/idempotence/dependencies, or scale/platform/CI and name the first diagnostic command. - Understand the mechanism behind each issue: the control node renders the template → AnsiballZ packages the module → SSH transfers it to a temp directory on the managed node → remote Python runs it → JSON is returned; know which error each step fails with.
- Be able to, on 3 disposable sshd containers (node1–node3),reproduce, diagnose, fix and clean up 14 typical faults.
- Answer 50 high-frequency Ansible interview questions using the structure “30-second answer → deep principles → production experience”, and handle follow-up questions.
- Use mock interviews (2-minute timer + self-assessment) to measure mastery and identify weak modules.
One-hour time allocation
| # | Time | Module | Core content | Animation · Interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Usage guide and fault lab environment | Install ansible with pipx; build 3 sshd containers; safety rules; five-step troubleshooting method | Environment self-check list | Set up the lab8 environment |
| 1 | 00–08 | A · Connection, Authentication and Privilege Escalation | Issues 1–12: UNREACHABLE, publickey, host keys, sshpass, become password, requiretty, Python interpreter, non-privileged become, remote temp directory, WinRM | Keyword filter · connection troubleshooting decision tree | 4 reproduction labs |
| 2 | 08–16 | A · Playbooks, Variables and Templates | Issues 13–25: undefined, precedence overrides, YAML quoting/booleans/octals, Jinja2 types, 2.19 strict conditionals, template trust, template syntax conflicts, loop, import/include, search paths, structural errors | Variable troubleshooting decision tree | 4 reproduction labs |
| 3 | 16–24 | A · Modules, Idempotence and Dependencies | Issues 26–38: shell always changed, boto3/psycopg2, missing collections, deprecation/FQCN, handlers, check mode, apt lock, systemd in containers, lineinfile, MODULE FAILURE, dependency conflicts | Module failure troubleshooting decision tree | 3 reproduction labs |
| 4 | 24–30 | A · Scale, Performance, Platforms and CI | Issues 39–50: slowness, fact timeouts, dead workers, sshd MaxStartups, long-running task disconnects, dynamic inventory, AWX projects, EE dependencies, Vault in CI, lint, world-writable config, locale | Platform/CI troubleshooting decision tree | 3 reproduction labs |
| 5 | 30–37 | B · Core Concepts and Architecture | Questions 1–13: agentless, execution flow, product family, idempotence, inventory, connection plugins, facts, comparison with Terraform, strategies, become, configuration | Mock interview (timed + self-assessment) | 2 scenario questions |
| 6 | 37–44 | B · Playbooks, Variables and Roles | Questions 14–25: variable precedence, handlers, import/include, roles, Jinja2, loops, block, magic variables, tags, collections, delegate/serial | Mock interview | 3 scenario questions |
| 7 | 44–52 | B · Modules, Plugins and Testing | Questions 26–38: module execution, custom modules/filters, plugin types, command/shell/raw, check/diff, lint/Molecule/ansible-test, debugging, performance, async, callbacks | Mock interview | 2 scenario questions |
| 8 | 52–60 | B · Security, Platforms and Scenario Design | Questions 39–50: Vault, external secrets, AWX/AAP, EE, EDA, CI/CD, zero downtime, 5,000-host scale, drift detection, supply chain, working with Terraform, troubleshooting methodology | Mock interview | 3 scenario questions |
| — | After class | Cheat sheet · Comprehensive drills | 50 “error → first command → fix” entries; 50 flashcards; 8 mixed faults; full mock interview | Full mock interview (10 random questions) | Final quiz: 12 questions |
Knowledge Coverage Matrix
| Target skill | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 | Key commands |
|---|---|---|---|---|---|---|---|---|---|
| SSH connections, keys and host fingerprints | ✓ | – | – | ✓ | ✓ | – | – | ✓ | ansible -m ping -vvvv · ssh -v
|
| become privilege escalation and sudo | ✓ | – | – | – | ✓ | – | – | ✓ | -K · become_user · sudo -l
|
| Python interpreter and module execution | ✓ | – | ✓ | – | ✓ | – | ✓ | – | ansible_python_interpreter · ANSIBLE_KEEP_REMOTE_FILES
|
| Variable precedence, YAML and Jinja2 | – | ✓ | – | – | – | ✓ | – | – | ansible-inventory --host · debug: var=
|
| 2.19+ template engine changes | – | ✓ | – | – | – | ✓ | – | – | ALLOW_BROKEN_CONDITIONALS · | bool
|
| Idempotence, handlers, check/diff | – | – | ✓ | – | ✓ | ✓ | ✓ | ✓ | changed_when · --check --diff
|
| Collections, dependencies and execution environments | – | – | ✓ | ✓ | – | ✓ | – | ✓ | ansible-galaxy collection list · ansible-builder
|
| Performance and scale | – | – | – | ✓ | ✓ | – | ✓ | ✓ | forks · pipelining · profile_tasks
|
| Vault and secrets | – | – | – | ✓ | – | – | – | ✓ | ansible-vault · --vault-id · no_log
|
| AWX/AAP, EDA, CI/CD | – | – | – | ✓ | – | – | – | ✓ | ansible-navigator · ansible-rulebook
|
| Testing: lint, Molecule, ansible-test | – | – | – | ✓ | – | – | ✓ | ✓ | ansible-lint · molecule test
|
| Scenario design (rolling updates, scale, drift) | – | – | – | – | – | ✓ | – | ✓ | serial · max_fail_percentage
|
How to use this lesson
- Go to the corresponding module's quick reference, paste the most distinctive words from the error (such as
publickey,requiretty,undefined,boto3) into the search box. - Click a row to jump to the issue details, then follow “diagnostic command → compare with sample output → fix”.
- If you are not sure which area it belongs to, use the animated paged troubleshooting decision tree.
- First look at the quick reference table to pick out questions you are not confident about.
- Use mock interview: random questions, a 2-minute countdown, answer first and check later, self-assess as “answered / partial / didn't know”; results are stored locally in the browser.
- Answer structure: conclusion → principle → commands/configuration → pitfalls encountered in production.
- Cheat sheetSummarizes all 50 issues; can be printed and pinned at your desk.
- Read through the night beforeinterview flashcards.
- Comprehensive drills: 8 mixed faults + full mock interview + 12-question final quiz.
Entry structure for Parts A / B
Symptom (raw error message) → root cause (mechanism level) → diagnostic command → sample expected output → fix → prevention and best practices → see Lesson N. Error messages use the wording actually output by ansible-core where possible; since 2.19 many template/condition-related errors have been reworded, so wording varies by version, which is noted in each entry.
30-second answer → in-depth answer (principles, code) → common follow-up questions from interviewers → bonus points → common wrong answers. Difficulty:BeginnerIntermediateAdvanced.
Relationship to the first seven lessons
| Lesson | Most-referenced content in this lesson |
|---|---|
| Lesson 1 Core Foundations | Architecture and execution flow, inventory and connections, ad-hoc, idempotence, variables and facts, handlers, Jinja2 templates |
| Lesson 2 Production Readiness | Roles, collections, variable precedence, Vault, block/rescue, check/diff, ansible-lint/Molecule, execution environments |
| Lesson 3 Azure · Lesson 4 AWS | Cloud collection authentication, azure_rm / aws_ec2 dynamic inventory, SSM connection plugin, Key Vault / Secrets Manager |
| Lesson 5 Automation Operations | CI pipelines, GitHub Actions + OIDC, AWX/AAP, EDA, credentials and RBAC |
| Lesson 6 Architecture in Practice | Multi-layer inventory, systemd services, PostgreSQL, serial rolling updates, delegate_to zero downtime |
| Lesson 7 Deep Troubleshooting | -vvvv methodology, debugger, deep dive into connections/privileges, forks/pipelining/fact cache, strategies and async, callbacks, custom plugins |
Content not covered in this lesson (where to learn it)
- Network device automation (
network_cli,httpapi, cisco.ios, etc.) specific errors: see the official Ansible Network Automation guide. - Deep Windows operations (DSC, domain controllers, Kerberos delegation): this lesson only covers WinRM/PSRP/SSH connections in Issue 12 and Interview Question 7; full coverage is in the official Windows Guide.
- Full details of writing collection tests with ansible-test, and the process for publishing collections to Galaxy/Automation Hub: see the Ansible Developer Guide.
- AAP installation and upgrade troubleshooting (containerized installer, tuning automation mesh receptors): see the Red Hat AAP 2.6 documentation; this lesson only covers job-level failures.
- Terraform issues themselves: see the same repository's Terraform 8-hour course Lesson 8.
Module 0 · Usage Guide and Fault Lab Environment (Before Class)
- Lessons 1 and 2 completed (Lessons 3–7 optional; relevant entries include links).
- An Ubuntu 24.04 machine (VM or WSL2) as the control node, with Docker Engine installed (from the Docker course).
- Control node Python 3.12+ (ansible-core 2.21 requires 3.12–3.14; Ubuntu 24.04 ships with 3.12).
Connecting from the previous lesson
If you kept the node1–node3 containers and ~/ansible-lab directory from Lesson 1 Module 0, you can reuse them directly; to avoid polluting the earlier environment with fault experiments, this lesson builds a separate set with a lab8- prefix for the containers and directory ~/lab8, which you can delete as a whole when finished.
Step 1: Install Ansible on the control node
sudo apt-get update && sudo apt-get install -y pipx sshpass jq pipx ensurepath && exec $SHELL -l pipx install --include-deps ansible # community package 14.x (includes ansible-core 2.21 and common collections) pipx inject ansible ansible-lint # optional: needed for Issue 48 ansible --version | head -3
ansible [core 2.21.x] config file = None configured module search path = ['/home/azureuser/.ansible/plugins/modules', ...]
Step 2: Build 3 managed-node containers
mkdir -p ~/lab8/node && cd ~/lab8
ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_lab8 -C lab8
cp ~/.ssh/id_lab8.pub node/
cat > node/Dockerfile <<'EOF'
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y --no-install-recommends openssh-server sudo python3 acl \
&& rm -rf /var/lib/apt/lists/* && mkdir -p /run/sshd \
&& useradd -m -s /bin/bash ansible && echo 'ansible ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/ansible \
&& useradd -m -s /bin/bash ops && echo 'ops:lab8pass' | chpasswd && echo 'ops ALL=(ALL) ALL' > /etc/sudoers.d/ops \
&& chmod 440 /etc/sudoers.d/*
COPY id_lab8.pub /tmp/key.pub
RUN for u in ansible ops; do install -d -m 700 -o $u -g $u /home/$u/.ssh; \
install -m 600 -o $u -g $u /tmp/key.pub /home/$u/.ssh/authorized_keys; done
EXPOSE 22
CMD ["/usr/sbin/sshd","-D","-e"]
EOF
docker build -t lab8-node node/
docker network create lab8
for i in 1 2 3; do docker run -d --name lab8-node$i --hostname node$i --network lab8 -p 127.0.0.1:222$i:22 lab8-node; done
docker ps --filter name=lab8- --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
NAMES STATUS PORTS lab8-node3 Up 3 seconds 127.0.0.1:2223->22/tcp lab8-node2 Up 3 seconds 127.0.0.1:2222->22/tcp lab8-node1 Up 4 seconds 127.0.0.1:2221->22/tcp
sshd as PID 1,have no systemd: ansible.builtin.systemd/service modules will fail (this is exactly the material used to reproduce Issue 35). Experiments that need real systemd can use 3 small VMs or multipass instead (multipass launch 24.04 -n node1), and only the inventory needs to be updated ansible_host.Step 3: Inventory and configuration
cd ~/lab8 cat > inventory.ini <<'EOF' [web] node1 ansible_port=2221 node2 ansible_port=2222 [db] node3 ansible_port=2223 [all:vars] ansible_host=127.0.0.1 ansible_user=ansible ansible_ssh_private_key_file=~/.ssh/id_lab8 EOF cat > ansible.cfg <<'EOF' [defaults] inventory = inventory.ini forks = 10 callbacks_enabled = ansible.posix.profile_tasks [ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=accept-new EOF ansible all -m ping -o
node1 | SUCCESS => {"changed": false,"ping": "pong"}
node2 | SUCCESS => {"changed": false,"ping": "pong"}
node3 | SUCCESS => {"changed": false,"ping": "pong"}
On first connection StrictHostKeyChecking=accept-new automatically records the host fingerprint; after that, a changed fingerprint (e.g., after rebuilding a container) is still rejected — Issue 3 exploits exactly this. All three nodes are accessed via 127.0.0.1, and the known_hosts entries look like [127.0.0.1]:2221.
Safety rules (must read)
lab8-node* containers; do not point the lab playbooks at a real inventory. After each lab, restore using its “Cleanup” step, or simply rebuild the containers.- Passwords used in the labs
lab8pass, Vault passwordlab8-vaultare all dummy values; do not reuse them on any real system. - Before modifying
~/.ssh/known_hostsback up first:cp ~/.ssh/known_hosts ~/.ssh/known_hosts.bak. - On CI or shared machines, do not use
-vvvvtasks that output secrets (they print module arguments); in production, combine withno_log: true.
General five-step troubleshooting method (used throughout Part A)
| Step | Command | Question it answers |
|---|---|---|
| 1 Read the error | Find UNREACHABLE! / FAILED! / ERROR!, and msg,module_stderr,rc | : is it a connection failure, an execution failure, or a failure at parse time? |
| 2 Narrow the scope | --limit node1 · --start-at-task "name" · --step · --syntax-check | Is it one host or all of them? Which task? |
| 3 Increase verbosity | -vvv (module arguments/return values) · -vvvv (SSH command line and connection debugging) | What did Ansible actually execute? |
| 4 Check the actual variables and configuration | ansible-inventory --host node1 · ansible-config dump --only-changed · debug: var=x | What are the effective values? Where do they come from? |
| 5 Reproduce on site | ssh -v -p 2221 ansible@127.0.0.1 · ANSIBLE_KEEP_REMOTE_FILES=1 then run the module manually on the remote host | Bypass Ansible: is the problem still there? |
For deeper methods (debugger, callbacks, performance profiling), see Lesson 7.
Self-check list
Full cleanup (after the course)
docker rm -f lab8-node1 lab8-node2 lab8-node3; docker network rm lab8; docker rmi lab8-node ssh-keygen -R '[127.0.0.1]:2221'; ssh-keygen -R '[127.0.0.1]:2222'; ssh-keygen -R '[127.0.0.1]:2223' rm -rf ~/lab8 ~/.ssh/id_lab8 ~/.ssh/id_lab8.pub
Module 1 · Part A: Connection, Authentication and Privilege Escalation (Issues 1–12)
- Pinpoint a failure to a stage of task execution: TCP connection → SSH authentication → creating the remote temp directory → transferring AnsiballZ → become privilege escalation → Python execution.
- Distinguish
UNREACHABLE!(connection plugin failure, task not executed) fromFAILED!(module executed but failed). - Master
-vvvv,ssh -v,sudo -l,ansible_python_interpreterand other diagnostic methods. - Prerequisites:Lesson 1 Module 2 Inventory and Connections; importance ★★★★★ (the most common class of problems in production).
Enter error keywords (such as timed out,publickey,sudo,python, or winrm) to filter; click a row to jump to the matching entry in “Issue details”.
#1 fatal: [web1]: UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: ssh: connect to host 10.0.1.4 port 22: Connection timed out", "unreachable": true}
Symptom: some or all hosts fail at the first task (usually Gathering Facts) with UNREACHABLE!, and subsequent tasks no longer run on these hosts; in PLAY RECAP unreachable=1. Variants: Connection refused (no one listening on the port),No route to host,Could not resolve hostname web1: Name or service not known,Connection timed out during banner exchange.
Root cause:UNREACHABLE means the connection plugin (default ansible.builtin.ssh, calls the OpenSSH client) failed to establish a session; the module was not transferred. timed out Mostly network-level: security group/NSG/firewall dropping packets, private IP unreachable, a jump host is required; refused means sshd is not running or the port is wrong; resolve hostname means the inventory uses a hostname without ansible_host, and DNS cannot resolve it either.
Diagnostic commands
ansible-inventory --host web1 | jq '{ansible_host, ansible_port, ansible_user}' # actual address to connect to
ansible web1 -m ping -vvvv 2>&1 | grep -E 'ESTABLISH SSH|SSH: EXEC|timed out|refused'
nc -vz -w 5 10.0.1.4 22 # plain TCP probe
ssh -v -o ConnectTimeout=5 azureuser@10.0.1.4 true
{ "ansible_host": "10.0.1.4", "ansible_port": null, "ansible_user": "azureuser" }
<10.0.1.4> ESTABLISH SSH CONNECTION FOR USER: azureuser
<10.0.1.4> SSH: EXEC ssh -vvv -C -o ControlMaster=auto ... -o ConnectTimeout=10 ... 10.0.1.4 '/bin/sh -c ...'
nc: connect to 10.0.1.4 port 22 (tcp) timed out: Operation now in progress
Fix
- Network: allow the control node's egress IP → target port 22 (NSG/security group/host firewall); when accessing from a CI runner on a cloud private network, the runner must be in the same VNet/VPC or connected via VPN.
- Jump host:
ansible_ssh_common_args='-o ProxyJump=azureuser@bastion.example.com'(put it in group_vars). - If you don't want to open port 22 on AWS, switch to the
amazon.aws.aws_ssmconnection plugin (requires session-manager-plugin on the control node and an S3 bucket for file transfers; see Lesson 4). - Hostname: write
ansible_host=IPin the inventory, or fix DNS. - Slow network:
[defaults] timeout = 30(SSH connection timeout, default 10 seconds).
Prevention and best practices
- Generate the inventory from cloud APIs with a dynamic inventory plugin to avoid stale hand-written IPs (Issue 44).
- Add a
ansible.builtin.wait_for_connectionat the start of production playbooks (when creating VMs), or alert on unreachable in PLAY RECAP; when you need to tolerate some hosts being offline, useignore_unreachable: trueand list them in the report. - Since 2.19, become timeouts are also classified as unreachable (see Issue 6), so don't rely only on
ignore_errors.
#2 UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: azureuser@10.0.1.4: Permission denied (publickey).", "unreachable": true}
Symptom: TCP is reachable, but SSH authentication fails. The methods listed in parentheses are those the server allows; (publickey) means only key authentication is accepted.
Root causes (by frequency):① Wrong username: on Azure the common default is azureuser (set at creation time); on AWS Ubuntu it is ubuntu, on Amazon Linux it is ec2-user; if ansible_user is not set, the control node's local username is used (or the User in ~/.ssh/config ). ② Wrong private key: the ansible_ssh_private_key_file path is incorrect, or ssh-agent holds too many keys and the server hits MaxAuthTries before the correct key is offered. ③ Private key permissions too open, so OpenSSH refuses it (WARNING: UNPROTECTED PRIVATE KEY FILE!). ④ Public key not in the target user's ~/.ssh/authorized_keys, or directory permissions don't meet sshd's StrictModes requirements. ⑤ CI runner has not loaded the key.
Diagnostic commands
ansible web1 -m ping -vvvv 2>&1 | grep -E 'USER:|Offering|Authentications that can continue|identity file' ssh -v -i ~/.ssh/id_lab8 -p 2221 ansible@127.0.0.1 true 2>&1 | grep -E 'Offering|Accepted|denied' ls -l ~/.ssh/id_lab8 # must be 600 or 400 ssh-add -l # how many keys are in the agent
<10.0.1.4> ESTABLISH SSH CONNECTION FOR USER: andy ← used the local username! debug1: Offering public key: /home/andy/.ssh/id_ed25519 ED25519 SHA256:... debug1: Authentications that can continue: publickey -rw-rw-r-- 1 andy andy 411 Nov 15 03:00 /home/andy/.ssh/id_lab8 ← permissions too open
Fix
# group_vars/azure_vms.yml ansible_user: azureuser ansible_ssh_private_key_file: ~/.ssh/id_azure # when the agent has too many keys, use only the specified one ansible_ssh_common_args: "-o IdentitiesOnly=yes"
chmod 600 ~/.ssh/id_azure; on the target host, check that ~/.ssh is 700 and authorized_keys is 600 with the correct owner; check the sshd log journalctl -u ssh -n 20 (on Ubuntu 24.04 the service name is ssh), in the Authentication refused: bad ownership or modes entries.
Prevention and best practices
- Put
ansible_userin group_vars rather than relying on the local username; in CI inject the private key via secrets andchmod 600. - When VMs are created (Terraform/cloud-init), distribute the deployment user and public key uniformly; use
ansible.posix.authorized_keyto manage public key rotation. - A better approach: SSH certificates (short-lived certificates signed by a CA), or AWS SSM or Azure Bastion, to avoid long-lived private keys scattered around.
#3 UNREACHABLE! … @@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@ … Host key verification failed.
Symptom: After a host is rebuilt (VM redeployed, container recreated, IP reused by another machine), Ansible fails to connect with a long OpenSSH warning in msg, ending in Host key verification failed.. Another variant: on first connection, the fingerprint is unknown and there is no TTY to confirm, which also produces Host key verification failed.
Root cause: Ansible defaults to host_key_checking = True, handing off to OpenSSH, which verifies the server host key per ~/.ssh/known_hosts . A changed host key may be a normal rebuild or a man-in-the-middle attack; SSH cannot tell them apart, so it refuses the connection. Reused cloud IPs and autoscaled instances make this especially common.
Diagnostic commands
ssh-keygen -F '[127.0.0.1]:2221' # old fingerprint recorded in known_hosts ssh-keyscan -p 2221 127.0.0.1 2>/dev/null | ssh-keygen -lf - # server's current fingerprint # out-of-band check: find the new fingerprint in the cloud console serial log / boot log and confirm it is a “normal rebuild”
[127.0.0.1]:2221 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK...old 256 SHA256:Xq3v...new [127.0.0.1]:2221 (ED25519)
Fix
ssh-keygen -R '[127.0.0.1]:2221' # remove the old entry (after confirming it was a normal rebuild) ssh-keyscan -p 2221 127.0.0.1 >> ~/.ssh/known_hosts # or let accept-new record it on first connection
For short-lived hosts, it is recommended in ansible.cfg , using ssh_args = ... -o StrictHostKeyChecking=accept-new: accept on first connection, still reject changes.
Prevention and best practices
- Do not set it globally in production
host_key_checking = False/ANSIBLE_HOST_KEY_CHECKING=False— it disables the man-in-the-middle protection; if it is used only in disposable CI test environments, state this in code review. - When hosts are created by Terraform/cloud-init, pre-generate host keys or use SSH host certificates (
@cert-authority), so the control node trusts the CA instead of per-host fingerprints. - In AWX, each job runs in a fresh container (EE), so known_hosts is not persisted; accept-new or a host certificate policy is even more necessary.
#4 Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host.
Symptom: Using -k/--ask-pass or ansible_password for password login reports the error above; another related error is to use the 'ssh' connection type with passwords or pkcs11_provider, you must install the sshpass program (wording varies slightly between versions).
Root cause: The OpenSSH client does not accept a password passed as an argument, so Ansible's ssh connection plugin relies on the sshpass program to feed the password to ssh. sshpass cannot handle the interactive prompt “Do you trust this new host fingerprint?”, so when the fingerprint is unknown and host key checking is on, Ansible refuses. Without sshpass installed, you get a second error.
Diagnostic commands
command -v sshpass || echo "sshpass not installed" ssh-keygen -F '[127.0.0.1]:2221' >/dev/null && echo "fingerprint known" || echo "fingerprint unknown" ansible-config dump | grep -E '^HOST_KEY_CHECKING'
sshpass not installed fingerprint unknown HOST_KEY_CHECKING(default) = True
Fix
sudo apt-get install -y sshpass ssh-keyscan -p 2221 127.0.0.1 >> ~/.ssh/known_hosts # first register the fingerprint (after verifying it) ansible node1 -u ops -k -m ping # enter lab8pass at the prompt
When you only need a password for first-time bootstrap: use a bootstrap playbook to log in with the password and deploy the public key (ansible.posix.authorized_key), then switch everything to key-based authentication.
Prevention and best practices
- Disable SSH password login in production (
PasswordAuthentication no); use password authentication only for one-time bootstrapping. - Do not put
ansible_passwordin plaintext in the inventory; if you must use it, store it in Vault (Issue 47) or an AWX credential. - The paramiko connection plugin (
-c paramiko) does not depend on sshpass, but it is less capable and slower than OpenSSH, so use it only as a temporary workaround.
#5 fatal: [node1]: FAILED! => {"msg": "Missing sudo password"}
Symptom: A task with become: true fails with an error asking for the sudo password; tasks on the same machine that do not escalate privileges run normally.
Root cause: The remote user has no NOPASSWD entry in sudoers, so sudo asks for a password, and Ansible was not given a become password (neither -K/--ask-become-pass nor ansible_become_password). Ansible detects the sudo password prompt and fails immediately instead of waiting.
Diagnostic commands
ansible node1 -u ops -m command -a 'sudo -n true' # -n: fail immediately instead of prompting when a password is needed
ansible node1 -u ops -m command -a 'sudo -l -n'
ansible-inventory --host node1 | jq 'with_entries(select(.key|test("become")))'
node1 | FAILED | rc=1 >>
sudo: a password is required
{}
Fix
- Interactive run:
ansible-playbook site.yml -K. - Automated runs: put
ansible_become_passwordin a Vault-encrypted group_vars (ansible_become_password: "{{ vault_become_password }}"), or enter the Privilege Escalation Password in the Machine credential in AWX. - Configure a precise NOPASSWD rule for a dedicated deployment account (using
community.general.sudoersor a template +validate: 'visudo -cf %s').
Prevention and best practices
- A dedicated deployment account + key authentication + NOPASSWD is the most common production practice; combine it with sudo log auditing (
/var/log/auth.log). - When editing sudoers,always use
validate, since a single syntax error can break all become and even lock you out.
#6 "Incorrect sudo password" / "Timeout (12s) waiting for privilege escalation prompt: "
Symptom: A become password was provided, but a wrong password error is reported; or after waiting about ten seconds, it reports a timeout waiting for the privilege escalation prompt.
Root cause:Incorrect sudo password: the Vault holds an old password; different hosts need different passwords but share one variable; passwords with special characters get truncated in YAML (e.g., starting with %,@, or { and not quoted). Timeout: Ansible matches a random prompt string against sudo output, so the following cases fail to match: a custom Defaults passprompt or a lecture printed on first use; PAM (LDAP/SSSD/MFA) is slow or asks for extra interaction; sudo's reverse lookup of the local hostname is slow (sudo: unable to resolve host node1); become_method prompts that mismatch (e.g., the target host only has doas or requires su). The timeout is determined by the timeout configuration.
Diagnostic commands
ansible node1 -u ops -K -b -m command -a id -vvvv 2>&1 | grep -E 'BECOME|sudo -H -S' ssh -p 2221 ops@127.0.0.1 'time sudo -k -S true' <<< 'lab8pass' # measure sudo duration manually ssh -p 2221 ops@127.0.0.1 'grep -rE "passprompt|lecture" /etc/sudoers /etc/sudoers.d 2>/dev/null; getent hosts $(hostname)'
<127.0.0.1> SSH: EXEC ssh ... '/bin/sh -c '"'"'sudo -H -S -p "[sudo via ansible, key=kqx...] password:" -u root /bin/sh -c ... real 0m14.211s ← sudo alone took 14 seconds (hostname resolution/LDAP) sudo: unable to resolve host node1: Temporary failure in name resolution
Fix
- Password issues:
ansible-vault viewverify; override per host withansible_become_password; always quote passwords in YAML. - Timeout: fix
/etc/hostsin the local hostname and PAM/SSSD performance; if necessary, increase[defaults] timeout; remove the custom passprompt;become_methodadjust it to match how the target host actually behaves. - Note for 2.19+: become timeouts are treated as unreachable errors; to tolerate them, use
ignore_unreachableinstead ofignore_errors(from the 2.19 porting guide).
Prevention and best practices
- When building images, make sure
/etc/hostsincludes the local hostname; cloud-initmanage_etc_hosts: true. - For automation accounts, use NOPASSWD and restrict the commands they can run; avoid putting interactive PAM (MFA) on the automation path.
See Lesson 7 Module 3.
#7 "module_stderr": "sudo: sorry, you must have a tty to run sudo\n"
Symptom: After enabling pipelining = True for speed, all become tasks fail on some older RHEL/CentOS hosts.
Root cause: sudoers contains Defaults requiretty (enabled by default on RHEL 6 and some hardened baselines), which requires sudo to run in a TTY. With pipelining, Ansible does not upload the module file; instead it feeds it via stdin in the SSH session directly to the remote sudo … python3, which has no TTY, so sudo refuses. Without pipelining, the module is uploaded first and then executed; the ssh plugin allocates a TTY by default with -tt a TTY, so it is unaffected.
Diagnostic commands
ansible legacy -b -m raw -a 'grep -rn requiretty /etc/sudoers /etc/sudoers.d' -o ansible-config dump --only-changed | grep -i pipelining
rhel6-01 | CHANGED | rc=0 | (stdout) /etc/sudoers:56:Defaults requiretty ANSIBLE_PIPELINING(/home/andy/proj/ansible.cfg) = True
Fix
# Remove requiretty with one task run without pipelining (validate first)
- name: Remove requiretty
ansible.builtin.lineinfile:
path: /etc/sudoers
regexp: '^Defaults\s+requiretty'
state: absent
validate: 'visudo -cf %s'
become: true
vars:
ansible_pipelining: false
or set this in group_vars for this set of hosts ansible_pipelining: false; or exempt only the deployment user: Defaults:deploy !requiretty.
Prevention and best practices
- pipelining significantly reduces SSH round trips per task (Lesson 7) and is a recommended optimization; before enabling it, check requiretty across your hosts.
- Modern RHEL no longer enables requiretty by default; if your security baseline requires it, enable it only for interactive users.
See Lesson 7 Module 4.
#8 "module_stderr": "/bin/sh: 1: /usr/bin/python: not found\n", "msg": "The module failed to execute correctly, you probably need to set the interpreter. See stdout/stderr for the exact error", "rc": 127
Symptom: On newly created Ubuntu 24.04 / Debian 12 hosts, all modules fail with rc=127.
Root cause: Apart from raw,script almost all modules require Python on the managed node. Common causes: ① leftover old configuration in the inventory ansible_python_interpreter=/usr/bin/python, while modern distributions only have /usr/bin/python3; ② minimal images (containers, Alpine, some minimal cloud images) without Python installed. If it is not set explicitly, Ansible performs interpreter discovery interpreter discovery (default auto), searching for Python by platform, which may produce a “discovered Python interpreter” warning.
Diagnostic commands
ansible-inventory --host node1 | jq .ansible_python_interpreter ansible node1 -m raw -a 'command -v python3 python; python3 --version' ansible node1 -m setup -a 'filter=ansible_python*' | grep -A3 executable
"/usr/bin/python" /usr/bin/python3 Python 3.12.3
Fix
# 1) delete the outdated override, or change it to python3 / auto_silent
ansible_python_interpreter: auto_silent
# 2) hosts without Python: bootstrap first with raw, without gathering facts
- hosts: new_hosts
gather_facts: false
become: true
tasks:
- name: Bootstrap python3
ansible.builtin.raw: test -e /usr/bin/python3 || (apt-get update && apt-get install -y python3)
changed_when: false
- name: Gather facts now
ansible.builtin.setup:
Prevention and best practices
- Do not hard-code the interpreter path globally; set it per group only when truly needed (e.g., a Python with dependencies in a venv).
- Golden images include python3; for container targets, prefer the
community.docker.dockerconnection plugin, or build the image instead of “configuring the container”.
#9 On old systems, modules report SyntaxError (managed node Python version is lower than ansible-core requires)
Symptom: After upgrading the control node to ansible-core 2.21, all modules fail on CentOS 7 / RHEL 7 / older Ubuntu hosts. module_stderr in the output is a Python SyntaxError error (such as future feature annotations is not defined,invalid syntax) or a message that the Python version is unsupported; the exact wording depends on the remote Python version and module, so use actual output as the reference.
Root cause: Module code runs on the managed node's Python . Each ansible-core version has a minimum Python requirement for managed nodes: 2.21 requires managed-node Python 3.9–3.14 (control node 3.12–3.14). Old interpreters such as Python 2.7 and 3.6 cannot parse new module code. Interpreter discovery may find exactly the old system Python.
Diagnostic commands
ansible legacy -m raw -a 'ls /usr/bin/python* ; /usr/bin/python3 -V' -o ansible --version | grep -E 'core|python version'
centos7-01 | CHANGED | rc=0 | (stdout) /usr/bin/python /usr/bin/python2.7 /usr/bin/python3 Python 3.6.8 ansible [core 2.21.x] python version = 3.12.3 ...
Fix
- If you can upgrade: install a supported Python on the target (for example, the
python3.11/python3.12package on RHEL 8), and setansible_python_interpreter: /usr/bin/python3.11per group. - For legacy systems that cannot be upgraded, keep an execution environment pinned to an older ansible-core (EE image or standalone venv) for them, and run jobs for this group of hosts with a different EE in AWX; also make a decommissioning plan.
- Read-only collection tasks can temporarily be completed with
raw.
Prevention and best practices
- Before upgrading ansible-core, read the corresponding porting guide and support matrix, and run Molecule in CI against the oldest target system.
- Record the Python version of each host in the asset inventory (fact cache) and batch-check it before upgrading.
#10 Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: chmod: invalid mode: 'A+user:postgres:rx:allow' …)
Symptom:become_user: postgres Tasks that run as (or as non-root users such as www-data, app) fail; become_user: root running as root is normal. The second half of the error varies by system and may be setfacl: command not found,chown … Operation not permitted , or the chmod error above, with a link to the official docs page “Risks of becoming an unprivileged user”.
Root cause: The module file is uploaded by the SSH user (such as ansible) to its temp directory, then switches to postgres to execute it; postgres the target user must be able to read it, but it must not be made world-readable (insecure). Ansible tries in order: setfacl ACL grant → chown (requires privilege) → macOS's chmod +a → shared group's chgrp… if all fail, it reports an error. The most common cause is that the target host does not have the acl package installed.
Diagnostic commands
ansible db -m raw -a 'command -v setfacl || echo no-setfacl' -o ansible db -b --become-user postgres -m command -a whoami -vvv 2>&1 | grep -E 'setfacl|chown|chmod' | head
node3 | CHANGED | rc=0 | (stdout) no-setfacl <127.0.0.1> EXEC /bin/sh -c 'setfacl -m u:postgres:r-x ~/.ansible/tmp/ansible-tmp-.../ .../AnsiballZ_command.py ...'
Fix
- Preferred: install
aclon the target (Debian/Ubuntuapt install acl, RHELdnf install acl). - Or enable
pipelining: the module is passed tosudo -u postgres python3via stdin, so no temporary file is needed (note the requiretty issue in #7). - Not recommended:
allow_world_readable_tmpfiles(module files may contain secret arguments).
Prevention and best practices
- Add
aclto the base role or golden image; in the Lesson 6 PostgreSQL role,become_user: postgresdepends on this. - Operations that can be done as root (such as chown after writing a config file) do not need to switch to a non-privileged user.
#11 "msg": "Failed to create temporary directory. In some cases, you may have been able to authenticate and did not have permissions on the target directory. Consider changing the remote tmp path in ansible.cfg to a path rooted in \"/tmp\" …"
Symptom: Authentication succeeds, but the first step of creating the remote temp directory ~/.ansible/tmp fails; the error includes the failed ( umask 77 && mkdir -p ... ) command and exited with result 1.
Root cause: Without pipelining, every task must create a remote_tmp (default ~/.ansible/tmp). Failure reasons: home directory does not exist or is not writable (LDAP users on first login have no home directory; home directory on a read-only or full NFS share); disk full or inode exhaustion; wrong home directory owner; SELinux denial. Also, when remote_tmp points to a path mounted with noexec the /tmp option, the module can be written but fails to execute.
Diagnostic commands
ansible node1 -m raw -a 'echo $HOME; ls -ld ~ ~/.ansible 2>&1; df -h ~; df -i ~; findmnt -no OPTIONS /tmp' ansible node1 -m ping -vvv 2>&1 | grep -A2 'mkdir -p'
/home/ansible drwxr-xr-x 2 root root 4096 Nov 15 03:00 /home/ansible ← owner is root! /dev/sda1 30G 30G 0 100% / ← or the disk is full
Fix
- Fix the home directory owner/space:
chown -R ansible: /home/ansible; clean up the disk. - For accounts without a home directory: set
remote_tmp = /var/tmp/.ansible-${USER}/tmpin ansible.cfg (make sure this mount point allows execution). - Enabling pipelining means most modules no longer need a remote temp file.
Prevention and best practices
- Give automation accounts a local home directory, not on NFS; alert on root partition and inode usage.
- When troubleshooting, use
ANSIBLE_KEEP_REMOTE_FILES=1to keep the remote temp files, so you can see directly where the module landed (Lesson 7).
See Lesson 7 Module 1.
#12 WinRM: winrm or requests is not installed: No module named 'winrm' / ntlm: the specified credentials were rejected by the server / ssl: … CERTIFICATE_VERIFY_FAILED
Symptom: When managing Windows hosts, connections fail; the three most common errors (all of type UNREACHABLE): missing Python libraries on the control node; authentication rejected; HTTPS certificate verification failed. There is also ssl: HTTPSConnectionPool(host='10.0.2.5', port=5986): Max retries exceeded with url: /wsman (a network/listener problem).
Root cause: The WinRM connection plugin runs on the control node, and depends on pywinrm (NTLM/Kerberos/CredSSP need extra dependencies); when installed with pipx, it must go into Ansible's venv rather than the system Python. Authentication failures are often caused by inconsistent local vs. domain account name formats (DOMAIN\user vs user@DOMAIN.COM), or a transport that does not match what the server allows (Basic is disabled by default). Certificate errors occur because the WinRM HTTPS listener uses a self-signed certificate.
Diagnostic commands
pipx runpip ansible list 2>/dev/null | grep -iE 'pywinrm|requests' nc -vz 10.0.2.5 5986 ansible win -m ansible.windows.win_ping -vvvv 2>&1 | grep -E 'ESTABLISH WINRM|transport|rejected|SSL' # On Windows: winrm enumerate winrm/config/Listener
(no output: pywinrm is not in ansible's venv) Connection to 10.0.2.5 5986 port [tcp/*] succeeded!
Fix
pipx inject ansible pywinrm # Kerberos additionally needs the system krb5 library and pywinrm[kerberos]
# group_vars/windows.yml
ansible_connection: winrm # or psrp (ansible.windows), or ssh (Windows OpenSSH)
ansible_port: 5986
ansible_winrm_transport: ntlm # prefer kerberos in domain environments
ansible_user: 'CORP\svc_ansible'
ansible_password: "{{ vault_win_password }}"
ansible_winrm_server_cert_validation: validate # use ignore only for lab environments with self-signed certificates
ansible_winrm_ca_trust_path: /etc/pki/corp-ca.pem
Prevention and best practices
- Pre-install pywinrm/pypsrp in the EE image (Issue 46).
- In production, enable the HTTPS listener + enterprise CA certificate + Kerberos; do not enable Basic over HTTP.
- Newer ansible-core also officially supports connecting via the OpenSSH server built into Windows (
ansible_connection: ssh+ansible_shell_type: powershell), which can unify the connection method across Linux and Windows; for specifics, follow the official Windows Guide.
See Lesson 1 Module 2; for Windows management, see the official Ansible Windows Guide.
Connection and privilege escalation troubleshooting decision tree
Select the symptom you see and step through to get diagnostic commands and conclusions; each conclusion corresponds to a real stage in the execution chain and can jump to the issue details.
~/lab8 and lab8-node1..3. Each lab gives “reproduce → diagnose → fix → clean up”.Lab 1-A: host key changed (#3)
cd ~/lab8 && cp ~/.ssh/known_hosts ~/.ssh/known_hosts.bak ansible node1 -m ping -o && ssh-keygen -F '[127.0.0.1]:2221' | head -1
docker exec lab8-node1 sh -c 'rm -f /etc/ssh/ssh_host_* && ssh-keygen -A' docker restart lab8-node1 && sleep 2 ansible node1 -m ping
node1 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: @@@@@@@@@@@@@@@@@@@@...\r\n@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n... Host key verification failed.",
"unreachable": true
}Note: containers started from the same image share the host keys generated at build time; this is itself an anti-pattern for image building (real environments should generate keys on first boot).
ssh-keyscan -p 2221 127.0.0.1 2>/dev/null | ssh-keygen -lf - # compare with ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub inside the container docker exec lab8-node1 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub ssh-keygen -R '[127.0.0.1]:2221' ansible node1 -m ping -o # re-record with accept-new
node1 | SUCCESS => {"changed": false,"ping": "pong"}cp ~/.ssh/known_hosts.bak ~/.ssh/known_hosts).Lab 1-B: Missing sudo password (#5)
ops user that requires a password:ansible node1 -u ops -b -m command -a id
node1 | FAILED! => {
"msg": "Missing sudo password"
}ansible node1 -u ops -m command -a 'sudo -n -l'
node1 | FAILED | rc=1 >> sudo: a password is required
ansible node1 -u ops -b -K -m command -a id # BECOME password: lab8pass mkdir -p host_vars && echo 'lab8-vault' > .vault_pass && chmod 600 .vault_pass ansible-vault encrypt_string --vault-password-file .vault_pass 'lab8pass' --name ansible_become_password > host_vars/ops_demo.yml cat host_vars/ops_demo.yml | head -3
node1 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
ansible_become_password: !vault |
$ANSIBLE_VAULT;1.1;AES256
6235...In a real project, put this variable in the vars file of the corresponding host/group, and provide the password with --vault-password-file or vault-id (Issue 47).
rm -f host_vars/ops_demo.yml (keep .vault_pass for use in Lab 4-C).Lab 1-C: Interpreter does not exist (#8)
ansible node2 -m ping -e ansible_python_interpreter=/usr/bin/python
node2 | FAILED! => {
"changed": false,
"module_stderr": "/bin/sh: 1: /usr/bin/python: not found\n",
"module_stdout": "",
"msg": "The module failed to execute correctly, you probably need to set the interpreter.\nSee stdout/stderr for the exact error",
"rc": 127
}docker exec lab8-node2 sh -c 'apt-get remove -y python3 python3-minimal >/dev/null 2>&1; command -v python3 || echo gone' ansible node2 -m ping
gone
node2 | FAILED! => { ... "module_stderr": "... python3: not found ..." ... }With no Python at all, interpreter discovery cannot find an interpreter either; the exact msg wording varies by version.
ansible node2 -b -m raw -a 'apt-get update -qq && apt-get install -y -qq python3 >/dev/null && python3 -V' ansible node2 -m ping -o
node2 | CHANGED | rc=0 | (stdout) Python 3.12.3
node2 | SUCCESS => {"changed": false,"ping": "pong"}docker rm -f lab8-node2 && docker run -d --name lab8-node2 --hostname node2 --network lab8 -p 127.0.0.1:2222:22 lab8-node.Lab 1-D: Non-privileged become and ACL (#10)
ansible node3 -b -m user -a 'name=appsvc system=true' ansible node3 -b -m apt -a 'name=acl state=absent'
ANSIBLE_PIPELINING=0 ansible node3 -b --become-user appsvc -m command -a whoami
node3 | FAILED! => {
"msg": "Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: chmod: invalid mode: 'A+user:appsvc:rx:allow' ...). For information on working around this, see https://docs.ansible.com/...#risks-of-becoming-an-unprivileged-user"
}The err in brackets depends on the method Ansible tried last; use actual output as the reference.
ANSIBLE_PIPELINING=1 ansible node3 -b --become-user appsvc -m command -a whoami # option 1: pipelining ansible node3 -b -m apt -a 'name=acl state=present' # option 2: reinstall acl ANSIBLE_PIPELINING=0 ansible node3 -b --become-user appsvc -m command -a whoami
node3 | CHANGED | rc=0 >>
appsvc
node3 | CHANGED => {"changed": true, ...}
node3 | CHANGED | rc=0 >>
appsvcansible node3 -b -m user -a 'name=appsvc state=absent remove=true'.Command question
1. You suspect Ansible is using the wrong username and private key when connecting. Write a command that shows only the SSH user Ansible actually uses and the full ssh command line.
Reference answer
ansible web1 -m ping -vvvv 2>&1 | grep -E 'ESTABLISH SSH CONNECTION FOR USER|SSH: EXEC'
then use ansible-inventory --host web1 to confirm where the variable comes from.
2. A batch of new Debian hosts has no Python. Write an ad-hoc command to install python3 (without relying on Python).
Reference answer
ansible newhosts -b -m raw -a 'test -e /usr/bin/python3 || (apt-get update && apt-get install -y python3)'
Scenario analysis question
To speed things up, the team enabled pipelining = True in ansible.cfg; as a result, on some hosts in the RHEL 7 data center everything fails (sudo: sorry, you must have a tty), while some become_user: postgres tasks that used to fail now succeed. Explain both phenomena.
Reference answer
pipelining passes the module to the remote sudo + python via the SSH session stdin, creating no temp file and allocating no TTY. ① On Defaults requiretty hosts, sudo refuses a non-TTY session (#7); you need to remove requiretty or disable pipelining for these hosts. ② The postgres task that failed before did so because the missing acl prevented postgres from reading the temp file (#10); pipelining needs no temp file, so it bypasses the problem. Long term: install acl in the base role and unify the sudoers baseline.
Teaching videos (titles and channels verified with YouTube oEmbed)
No verified video specifically on “Ansible connection and privilege escalation troubleshooting” was found. Below is a 3-minute storyboard that can be given to a video tool to generate or recorded by yourself (this courseware cannot directly generate video or MP3).
Scene: -vvvv output highlights “ESTABLISH SSH CONNECTION FOR USER: andy”. Narration: “The local username was used; this is the culprit behind Permission denied publickey.”
Scene: Figure 1-1 execution chain animation, lighting up the six stages in sequence. Narration: “Temp directory, transfer, privilege escalation, Python — each stage has its own error.”
Scene: Lab 1-D, before and after the pipelining toggle. Narration: “Non-privileged become needs ACL; pipelining can bypass it, but requiretty must be removed first.”
Official docs
Module 2 · Part A: Playbooks, Variables and Templates (Issues 13–25)
- Distinguish three failure timings: parse time (YAML/Playbook structure; ERROR before the whole run starts),task argument rendering time (Jinja2 evaluation on the control node),module execution time.
- Use
ansible-inventory,debug,type_debugto determine the actual value, type and source of a variable. - Understand the template engine changes since ansible-core 2.19: conditionals must be booleans, {{ }} cannot be nested inside conditionals, and only “trusted” templates are rendered.
- Prerequisites:Lesson 1 Module 5 Variables and Facts,Module 7 Jinja2 templates,Lesson 2 Module 3 Variable precedence; importance ★★★★★.
Enter keywords (such as undefined,quotes,Conditional,loop, or Could not find) to filter; click a row to jump to the details.
#13 fatal: [node1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'app_port' is undefined …"}
Symptom: The task fails while rendering arguments on the control node, reporting an undefined variable and giving the playbook file and line number. Since 2.19, the error is reworded in a form like Error while resolving value for 'dest': 'app_port' is undefined with the source location attached (wording varies by version; use actual output as the reference).
Root cause: Jinja2 evaluates for each host, and that host's scope has no such name: ① the variable is defined in group_vars/web.yml but the host is not in the web group; ② group_vars/host_vars must sit at the same level as the inventory file or playbook, otherwise they are not loaded; ③ spelling/case mismatch; ④ the variable comes from register but the task was skipped on this host or belongs to another play; ⑤ stricter since 2.19 (for example, result.exists is false accessing a non-existent attribute now raises an error).
Diagnostic commands
ansible-inventory --graph --vars | grep -B2 app_port # which group the variable is attached to ansible-inventory --host node3 | jq .app_port # can this host see it? ansible node3 -m debug -a 'var=app_port' ls -d group_vars host_vars; ansible-config dump | grep -E '^DEFAULT_HOST_LIST'
|--@web:
| |--node1
| | |--{app_port = 8000}
null
node3 | SUCCESS => { "app_port": "VARIABLE IS NOT DEFINED!" }
Fix
# provide sensible defaults inside the role (lowest precedence, can always be overridden)
# roles/myapp/defaults/main.yml
app_port: 8000
# truly optional parameters: use default or omit
- ansible.builtin.template:
src: app.env.j2
dest: /etc/myapp/app.env
mode: "{{ app_env_mode | default('0640') }}"
# required parameters: validate at the start and give a clear error
- ansible.builtin.assert:
that: [db_password is defined, db_password | length > 0]
fail_msg: "db_password is undefined; set it in Vault"
Prevention and best practices
- Each role declares all tunable parameters in
defaults/main.ymland pairs them withmeta/argument_specs.ymlto validate input automatically. - Do not disable
DEFAULT_UNDEFINED_VAR_BEHAVIOR(otherwise undefined variables silently become empty strings, pushing errors into production). - When a registered variable is skipped, subsequent references use
result is skippedorresult.stdout | default('').
#14 nginx_port changed to 8080 in group_vars, but it is still 80 after running (unexpected override by variable precedence)
Symptom: No error is reported, but the configuration value is not the one you set in the inventory variables; or one environment's value leaked into another environment.
Root cause: Variable precedence has more than twenty levels (see the official “Understanding variable precedence”). Common pitfalls: ① a role's vars/main.yml takes precedence over inventory group_vars/host_vars, so tunable parameters should be written in defaults/; ② a child group overrides the parent group, and sibling groups are merged in alphabetical order (the latter wins), which can be adjusted with ansible_group_priority ; ③ set_fact,include_vars has very high precedence; once set, it keeps overriding later plays; ④ -e extra vars are always highest; a -e left over from CI scripts silently overrides everything; ⑤ dictionaries default to wholesale replacement (hash_behaviour=replace), so keys in group_vars/all dictionaries are lost once replaced by a child group.
Diagnostic commands
grep -rn 'nginx_port' group_vars host_vars roles/*/defaults roles/*/vars playbooks/ 2>/dev/null ansible-inventory --host node1 | jq .nginx_port # value at the inventory level grep -rnE 'ansible-playbook .*(-e|--extra-vars)' .github/ Makefile scripts/ 2>/dev/null # leftover -e in CI ansible node1 -m debug -a 'var=nginx_port' -e @roles/nginx/vars/main.yml # simulate role vars overriding
group_vars/web.yml:2:nginx_port: 8080 roles/nginx/vars/main.yml:3:nginx_port: 80 ← role vars have higher precedence than group_vars 8080
Fix
- Move tunable parameters from
roles/*/vars/toroles/*/defaults/; keep only “should not be modified” internal constants in vars/ (such as OS-specific package names). - When dictionaries need merging, explicitly use
combine:nginx_conf: "{{ nginx_conf_defaults | combine(nginx_conf_overrides, recursive=True) }}", rather than changing the global hash_behaviour. - For environment isolation, use separate inventory directories (
inventories/prod/,inventories/staging/, each with its own group_vars).
Prevention and best practices
- Team convention: variables are defined only in three places — “inventory group_vars + role defaults + Vault”; scattering vars across playbooks is prohibited.
- Prefix variables with the role name (
nginx_portrather thanport), and ansible-lint'svar-naming[no-role-prefix]rule can check this. - In CI, run
--check --diffand review the diff; precedence issues will show up in the rendered configuration.
#15 ERROR! Syntax Error while loading YAML. … We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value.
Symptom:ansible-playbook It fails as soon as it starts, without executing any task; the error gives the file, line and column, and a caret symbol ^ pointing to the position, with a “missing quotes” hint and an example. (Since 2.19 the error prefix display format has changed; use actual output as the reference.)
Root cause: In YAML, { a value starting with {{ begins a flow mapping,msg: {{ greeting }} is read as a “dict inside a dict”, failing before Jinja2 gets involved. Other parse-time errors: mapping values are not allowed in this context (an unquoted value containing : ), tab indentation (found character '\t' that cannot start any token), inconsistent indentation at the same level, values starting with @,`, or % .
Diagnostic commands
ansible-playbook site.yml --syntax-check python3 -c 'import sys,yaml; yaml.safe_load(open(sys.argv[1]))' site.yml # pure YAML validation ansible-lint site.yml # yaml[*] and jinja[*] rules grep -nP '\t' site.yml # find tabs
ERROR! Syntax Error while loading YAML.
found unacceptable key (unhashable type: 'AnsibleMapping')
The error appears to be in '/home/andy/lab8/site.yml': line 6, column 13 ...
msg: {{ greeting }}
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. ...
Fix
- ansible.builtin.debug:
msg: "{{ greeting }}" # must quote values that start with {{
- ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
line: "PermitRootLogin: no" # also quote values containing ': '
- ansible.builtin.command: "echo {{ a }}:{{ b }}"
Prevention and best practices
- Enable a YAML language server + Ansible extension in your editor (the VS Code Ansible extension bundles ansible-lint).
- Run
yamllint/ansible-lintin pre-commit; the first CI step is--syntax-check.
#16 File permissions become --w----r-T (mode: 644 unquoted) / version 1.10 becomes 1.1 / "no" becomes False
Symptom: No error is reported, but the results are odd: the configuration file's permissions are --w----r-T; python_version: 3.10 the package installs as 3.1; the Norway country code country: NO becomes the boolean False.
Root cause: YAML decides types before Ansible does. ① mode: 644 is the decimal integer 644, which equals octal 1204 (sticky + w + r), and the file module uses it as a number; mode: 0644 in YAML 1.1 is parsed as octal, so the result is correct but unintuitive. ② 3.10 is a float equal to 3.1. ③ YAML 1.1, which Ansible uses, parses yes/no/on/off/true/false (several case-insensitive forms) into booleans.
Diagnostic commands
ansible node1 -m debug -a 'msg={{ [mode_var, mode_var | type_debug] }}' -e '{"mode_var": 644}'
ansible node1 -m stat -a 'path=/etc/myapp/app.conf' | grep -E '"mode"'
ansible-lint roles/ | grep -E 'risky-octal|yaml\[truthy\]'
node1 | SUCCESS => { "msg": [644, "int"] }
"mode": "1204",
roles/app/tasks/main.yml:12: risky-octal: Octal file permissions must contain leading zero or be a string
Fix
mode: "0644" # always write permissions as quoted strings (or write "u=rw,g=r,o=r") python_version: "3.10" # always quote version numbers country: "NO" service_enabled: true # use true/false for booleans consistently (ansible-lint yaml[truthy])
Prevention and best practices
- Make the ansible-lint
risky-octal,yaml[truthy]rules required CI checks. - In the role's
argument_specsdeclaretype: str, type errors are caught as soon as the run starts.
#17 Unexpected templating type error occurred on ({{ app_port + 1 }}): can only concatenate str (not "int") to str
Symptom: After the port is passed in via -e app_port=8000 , arithmetic or comparison fails; or when: replicas > 3 reports '>' not supported between instances of 'str' and 'int'; it can also be silently wrong (no error): a string comparison '10' > '9' evaluates to False.
Root cause:-e key=value Values passed in this form are always strings; values from command output (register 's stdout), environment variables and lookups are also strings. Jinja2 does no implicit type conversion. Conversely,{{ }} Ansible tries to convert rendered results back to native types by default (a string "8000" can become an integer in some contexts), so the same variable can have different types in different places.
Diagnostic commands
ansible node1 -m debug -a 'msg={{ app_port | type_debug }}' -e app_port=8000
ansible node1 -m debug -a 'msg={{ app_port | type_debug }}' -e '{"app_port": 8000}'
node1 | SUCCESS => { "msg": "str" }
node1 | SUCCESS => { "msg": "int" }
Fix
- ansible.builtin.set_fact:
next_port: "{{ app_port | int + 1 }}"
- ansible.builtin.debug: msg="scale out"
when: replicas | int > 3
# compare versions with the version test, not string comparison
- ansible.builtin.debug: msg="new enough"
when: ansible_facts.distribution_version is version('22.04', '>=')
When passing structured values, use JSON/YAML: -e '{"app_port": 8000}' or -e @vars/prod.yml.
Prevention and best practices
- In the role entry point, use
argument_specsto declaretype: int, and Ansible converts/validates automatically. - Explicitly filter all external input (-e, command output, API responses) before use:
| int,| bool,| from_json.
See Lesson 1 Module 7.
#18 Conditional result was 'yes' of type 'str', which evaluates to True. Conditionals must have a boolean result. (2.19+)
Symptom: After upgrading to ansible-core 2.19 or later (including 2.21), previously working when: conditionals fail. Two typical errors: the “Conditionals must have a boolean result” message above, and the error for a template nested in a condition, such as Syntax error in expression. Template delimiters are not supported in expressions: expected token ':', got '}'.
Root cause: In the 2.19 template engine, conditionals became stricter: ① when the result must be a real boolean. Previously, when: enable_tls (a string "yes"/"false") was judged by Python truthiness, and a non-empty "false" is also True; ② when is itself a Jinja2 expression, so it must not be wrapped in when: "{{ x }}"; ③ building expressions dynamically from templates is considered unsafe and is no longer supported. ALLOW_BROKEN_CONDITIONALS You can temporarily downgrade it to a warning.
Diagnostic commands
grep -rnE 'when:.*\{\{' roles/ playbooks/ # conditions with nested templates
ansible node1 -m debug -a 'msg={{ enable_tls | type_debug }}'
ansible-lint --profile production . | grep -E 'no-jinja-when|literal-compare'
roles/web/tasks/main.yml:21: when: "{{ enable_tls }}"
node1 | SUCCESS => { "msg": "str" }
Fix
# before (works on 2.18, fails on 2.19+)
when: "{{ enable_tls }}"
when: result.stdout # string
when: my_list # list
# after
when: enable_tls | bool
when: result.stdout | length > 0
when: my_list | length > 0
when: inventory_hostname in groups['web']
# temporary workaround for the upgrade only (ansible.cfg), remove after the fix [defaults] allow_broken_conditionals = True
Prevention and best practices
- Before upgrading, run
--checkor Molecule in CI with the new version, and read the 2.19 porting guide item by item. - Set boolean variables in defaults using
true/false, and always filter external input with| bool(since 2.19, theboolfilter warns about unrecognized input and will become an error in 2.23).
#19 Since 2.19, a template is “not rendered”: the output contains a literal {{ inventory_hostname }} (template trust)
Symptom: After upgrading to 2.19+, strings obtained from an API (uri), command output,slurp and similar sources that contain {{ … }}, which used to be rendered again, is now output as-is; by default raises no error (silently).
Root cause: 2.19 introduced template trust: only strings from trusted sources (playbooks, roles, variable files, etc.) are rendered as templates. Untrusted strings such as module return values may be referenced, but template expressions inside them are returned unchanged and never executed, which closes the risk of remote data being run as code on the control node. You can set _ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR to warning or error to find these places (see the porting guide for details).
Diagnostic commands
_ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR=warning ansible-playbook site.yml --limit node1 2>&1 | grep -i untrusted grep -rnE 'uri:|slurp:|register:' roles/ | head
[WARNING]: ... untrusted template ... (exact wording depends on actual output)
Fix
- Put templates that need rendering in the role's
templates/, and useansible.builtin.templatemodule orlookup('ansible.builtin.template', ...)to render. File templates are trusted. - For remote data, only do “data processing” (
from_json,regex_replace,combine), and pass the values to fill in as variables to a trusted template, instead of letting the remote side supply the template.
Prevention and best practices
- Treat “rendering remote data again” as a code smell. In code review, search for register results wrapped again in
{{ }}syntax. - During upgrade testing, temporarily enable the warning behavior, and keep the default once fixed.
#20 'dict object' has no attribute 'ansible_default_ipv4' (referencing facts of other hosts)
Symptom: The nginx upstream template on the web nodes contains {{ hostvars[item]['ansible_default_ipv4']['address'] }}, works on a full run, but fails when run with --limit web or --tags nginx , reporting that the attribute does not exist (the object name may appear as HostVarsVars object; exact wording depends on the actual output).
Root cause: Facts exist only after a host has taken part in the play and run Gathering Facts, in hostvars. --limit web If db/app hosts do not take part (for example with gather_facts: false or gather_subset a too-small batch size also causes this. Also, ansible_default_ipv4 can be an empty dict on hosts with multiple NICs or no default route.
Diagnostic commands
ansible-playbook site.yml --limit web -e 'x=1' --list-hosts
ansible node1 -m debug -a "msg={{ hostvars['node3'].keys() | select('match','ansible_') | list | length }}"
ansible node3 -m setup -a 'filter=ansible_default_ipv4'
node1 | SUCCESS => { "msg": 0 } ← no facts for node3
Fix
# option 1: gather facts for the referenced host first (even with --limit, use delegate_facts)
- name: Gather facts of app servers for templating
hosts: web
tasks:
- ansible.builtin.setup:
gather_subset: [network]
delegate_to: "{{ item }}"
delegate_facts: true
loop: "{{ groups['app'] }}"
run_once: true
# option 2: use inventory variables instead of facts (more stable)
# server {{ hostvars[item].ansible_host }}:8000;
# option 3: enable fact caching (jsonfile/redis) so --limit can still read the last facts
Prevention and best practices
- For cross-host references, prefer the address declared in the inventory (ansible_host or a custom private_ip), not runtime facts.
- Add a guard in templates:
{{ hostvars[item].ansible_host | default(item) }}.
#21 AnsibleError: template error while templating string: unexpected char '$' at 3. String: {{ $labels.instance }}
Symptom: When the template module deploys Prometheus alert rules, Helm values, Go templates or shell scripts that contain ${{ }} , Jinja2 raises a syntax error (e.g. unexpected char,unexpected '}',unexpected end of template etc.).
Root cause: These files also use {{ }} as template syntax, so Jinja2 tries to parse them.
Diagnostic commands
grep -nE '\{\{|\{%' roles/monitoring/templates/alerts.yml.j2 | head
ansible localhost -m debug -a "msg={{ lookup('template', 'roles/monitoring/templates/alerts.yml.j2') }}"
Fix
# option 1: output the raw block as-is
groups:
- name: node
rules:
- alert: InstanceDown
expr: up == 0
annotations:
summary: {% raw %}"{{ $labels.instance }} is down"{% endraw %}
runbook: "{{ runbook_base_url }}/instance-down" {# still an Ansible variable here #}
# option 2: if the file needs no Ansible variables, use copy instead of template
# option 3: if a variable value itself contains {{ }}, mark it !unsafe so Ansible does not render it
grafana_label_tpl: !unsafe '{{ $labels.job }}'
You can also change the delimiters on the template's first line: #jinja2: variable_start_string: '[[', variable_end_string: ']]'.
Prevention and best practices
- “Use copy for files without variables, and template only for files that contain variables.”
- Write unit tests for third-party template syntax: in CI, use
--check --diffto render once.
See Lesson 1 Module 7.
#22 Invalid data passed to 'loop', it requires a list, got this instead: … Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup.
Symptom: After rewriting with_* as loop it fails with an error, or looping over a dict fails with the same error.
Root cause:loop loop accepts only a list, unlike with_items which automatically flattens nested lists and splits comma-separated strings. lookup() By default it returns a comma-joined string, only query()/q() returns a list; for a dict, first convert it with dict2items to a list.
Diagnostic commands
ansible localhost -m debug -a "msg={{ lookup('ansible.builtin.fileglob', '/etc/*.conf') | type_debug }}"
ansible localhost -m debug -a "msg={{ query('ansible.builtin.fileglob', '/etc/*.conf') | type_debug }}"
localhost | SUCCESS => { "msg": "str" }
localhost | SUCCESS => { "msg": "list" }
Fix
- ansible.builtin.copy: { src: "{{ item }}", dest: /etc/myapp/ }
loop: "{{ query('ansible.builtin.fileglob', 'files/conf.d/*.conf') }}"
- ansible.builtin.user: { name: "{{ item.key }}", uid: "{{ item.value.uid }}" }
loop: "{{ users | dict2items }}" # users is a dict
- ansible.builtin.debug: { msg: "{{ item }}" }
loop: "{{ nested | flatten(levels=1) }}" # with_items flattens one level automatically, loop does not
Prevention and best practices
- When migrating
with_*, compare against the official “Migrating from with_X to loop” table and rewrite each one. - For large loops, use
loop_control: label:to keep output short and avoid printing large objects to the log (Issue 41).
See Lesson 1 Module 6.
#23 ansible-playbook --tags nginx finishes with "ok=0 changed=0": none of the tasks inside include_tasks ran
Symptom: Adding tags to include_tasks / include_role skips the internal tasks when running by tag; or import_tasks adding when, so only the first task runs and the rest are skipped; --list-tasks the included tasks are not visible.
Root cause:import_* It is static: it is expanded at parse time, and tags and when are copied to every subtask (when is evaluated for each task separately; if the first task changes the state a condition depends on, later tasks are skipped). include_* It is dynamic: it is loaded only when reached, tags and when apply only to the include statement itself, and the internal tasks have no nginx tag, so they are --tags nginx filtered out.
Diagnostic commands
ansible-playbook site.yml --list-tasks --tags nginx ansible-playbook site.yml --list-tags
play #1 (web): web TAGS: []
tasks:
include_tasks TAGS: [nginx] ← only the include itself, the internal tasks are not shown
Fix
# to select by tag → use a static import
- ansible.builtin.import_tasks: nginx.yml
tags: nginx
# must be dynamic (file name contains a variable, needs a loop) → use apply to pass the tags to the internal tasks
- ansible.builtin.include_tasks:
file: "{{ ansible_facts.os_family | lower }}.yml"
apply:
tags: nginx
tags: nginx # the include itself also needs the tag, otherwise it is never reached
# to evaluate when only once → use include or block instead of import
Prevention and best practices
- Use import by default (predictable, can be listed); use include only when you need dynamic behavior.
- After each change to tags, run
--list-tasks --tags Xas assertions in CI.
#24 Could not find or access 'nginx.conf.j2' Searched in: …/roles/web/templates/nginx.conf.j2 … on the Ansible Controller.
Symptom: template/copy/script cannot find the source file; the error lists every path it searched. The “on the Ansible Controller” note at the end means the source file is looked up on the control node (only on the managed node when remote_src: true is set).
Root cause: Relative paths are searched through a list of search paths: the current role's templates/ (or files/) → the directory of the current task file → the playbook directory, and so on. Common causes: the file is in another role; after include_role/include_tasks the relative-path base changed; file names differ in case; in AWX the project directory structure differs from local ones.
Diagnostic commands
ansible-playbook site.yml --limit node1 -vvvvv 2>&1 | grep -A8 'Searched in' find . -iname 'nginx.conf*'
Searched in: /home/andy/proj/roles/web/templates/nginx.conf.j2 /home/andy/proj/roles/web/nginx.conf.j2 /home/andy/proj/roles/web/tasks/templates/nginx.conf.j2 /home/andy/proj/roles/web/tasks/nginx.conf.j2 /home/andy/proj/templates/nginx.conf.j2 /home/andy/proj/nginx.conf.j2 ./roles/common/templates/Nginx.conf.j2 ← in another role, and the case differs
Fix
Move the template into the using role's templates/; to share it across roles, extract a standalone role or use "{{ role_path }}/../common/templates/x.j2" (not recommended, it creates coupling); keep file-name case consistent.
Prevention and best practices
- Follow the standard role directory structure; use
ansible-galaxy role initto generate the skeleton. - Molecule runs in a fresh container after checking out from the repository, so it exposes files that exist only on your machine early.
See Lesson 2 Module 1.
#25 ERROR! conflicting action statements: ansible.builtin.copy, ansible.builtin.template / 'tsaks' is not a valid attribute for a Play / this task 'ansible.builtin.apt' has extra params …
Symptom: The playbook fails at parse time and does not run. Three related errors: two modules in one task; a misspelled play keyword; or a module argument indented wrongly, so the arguments become a “free-form” string (has extra params, which is only allowed in the following modules: ansible.builtin.command, ansible.builtin.shell, …).
Root cause: All are valid YAML but do not match the playbook structure, caused by indentation or spelling. For example, the line under - name: is missing a -, so two tasks are merged into one dict; or the module arguments are written at the same indentation level as the module name.
Diagnostic commands
ansible-playbook site.yml --syntax-check ansible-lint site.yml # the syntax-check[specific] and schema[playbook] rules point to the exact location
ERROR! conflicting action statements: ansible.builtin.copy, ansible.builtin.template The error appears to be in '/home/andy/lab8/site.yml': line 8, column 7 ...
Fix
# wrong: two tasks missing the separating "-"
- name: Copy and template
ansible.builtin.copy: { src: a, dest: /tmp/a }
ansible.builtin.template: { src: b.j2, dest: /tmp/b }
# correct
- name: Copy a
ansible.builtin.copy: { src: a, dest: /tmp/a }
- name: Template b
ansible.builtin.template: { src: b.j2, dest: /tmp/b }
# wrong: arguments at the same level as the module
- name: Install nginx
ansible.builtin.apt:
name: nginx
# correct: arguments indented under the module
- name: Install nginx
ansible.builtin.apt:
name: nginx
Prevention and best practices
- Always use the “module name + indented dict arguments” form and avoid
key=valuefree-form strings; the ansible-lintno-free-formrule can enforce this. - Enable Ansible language server schema validation in your editor.
See Lesson 1 Module 4.
Decision tree for troubleshooting variables and templates
Start from one of three paths: “fails at startup / rendering fails / wrong value”; each conclusion links to an issue detail.
~/lab8/m2 ; use the Module 0 inventory (-i ../inventory.ini).Lab 2-A: YAML with missing quotes (#15)
mkdir -p ~/lab8/m2 && cd ~/lab8/m2
cat > quotes.yml <<'EOF'
- hosts: node1
gather_facts: false
vars:
greeting: hello
tasks:
- ansible.builtin.debug:
msg: {{ greeting }}
EOF
ansible-playbook -i ../inventory.ini quotes.yml --syntax-checkERROR! Syntax Error while loading YAML. found unacceptable key (unhashable type: 'AnsibleMapping') ... We could be wrong, but this one looks like it might be an issue with missing quotes. ...
sed -i 's/msg: {{ greeting }}/msg: "{{ greeting }}"/' quotes.yml
ansible-playbook -i ../inventory.ini quotes.ymlok: [node1] => {
"msg": "hello"
}Lab 2-B: role vars override group_vars (#14)
cd ~/lab8/m2 && mkdir -p roles/web/{vars,defaults,tasks} group_vars
echo 'nginx_port: 80' > roles/web/vars/main.yml
echo 'nginx_port: 8080' > group_vars/web.yml
cat > roles/web/tasks/main.yml <<'EOF'
- ansible.builtin.debug:
msg: "nginx_port={{ nginx_port }}"
EOF
printf -- '- hosts: web\n gather_facts: false\n roles: [web]\n' > prec.yml
cp ../inventory.ini . && ansible-playbook -i inventory.ini prec.yml | grep nginx_port "msg": "nginx_port=80"
"msg": "nginx_port=80"The inventory is copied to the current directory because group_vars must sit next to the inventory file (or the playbook) to be loaded.
ansible-inventory -i inventory.ini --host node1 | jq .nginx_port grep -rn nginx_port roles group_vars
8080 roles/web/vars/main.yml:1:nginx_port: 80 group_vars/web.yml:1:nginx_port: 8080
mv roles/web/vars/main.yml roles/web/defaults/main.yml ansible-playbook -i inventory.ini prec.yml | grep nginx_port ansible-playbook -i inventory.ini prec.yml -e nginx_port=9090 | grep nginx_port # -e always wins
"msg": "nginx_port=8080"
"msg": "nginx_port=9090"Lab 2-C: stricter conditionals in 2.19+ (#18)
cat > cond.yml <<'EOF'
- hosts: node1
gather_facts: false
vars:
enable_tls: "false"
tasks:
- name: Broken conditional (string)
ansible.builtin.debug: { msg: "TLS on" }
when: enable_tls
EOF
ansible-playbook -i inventory.ini cond.ymlfatal: [node1]: FAILED! => {"msg": "Conditional result was 'false' of type 'str', which evaluates to True. Conditionals must have a boolean result."}The error reveals a risk in older versions: the string "false" is True when evaluated for truth, so on 2.18 and earlier this task will run.
sed -i 's/when: enable_tls$/when: enable_tls | bool/' cond.yml ansible-playbook -i inventory.ini cond.yml | grep -E 'skipping|TLS on'
skipping: [node1]
when: "{{ enable_tls }}" and run again, which gives a Template delimiters are not supported in expressions -like error (exact wording depends on actual output).Lab 2-D: the octal trap of mode 644 (#16)
ansible node1 -b -m copy -a 'content="x\n" dest=/tmp/lab8-mode.txt' >/dev/null
cat > mode.yml <<'EOF'
- hosts: node1
gather_facts: false
become: true
tasks:
- ansible.builtin.file: { path: /tmp/lab8-mode.txt, mode: 644 }
EOF
ansible-playbook -i inventory.ini mode.yml >/dev/null; ansible node1 -m command -a 'ls -l /tmp/lab8-mode.txt'--w----r-T 1 root root 2 Nov 15 03:00 /tmp/lab8-mode.txt
sed -i 's/mode: 644/mode: "0644"/' mode.yml && ansible-playbook -i inventory.ini mode.yml >/dev/null ansible node1 -m command -a 'ls -l /tmp/lab8-mode.txt'
-rw-r--r-- 1 root root 2 Nov 15 03:00 /tmp/lab8-mode.txt
ansible node1 -b -m file -a 'path=/tmp/lab8-mode.txt state=absent'; rm -rf ~/lab8/m2Command questions
1. Write a command to check the value and type of a variable app_port on node1.
Reference answer
ansible node1 -m debug -a 'msg={{ [app_port, app_port | type_debug] }}'2. List the tasks that would run --tags nginx (without actually running them).
Reference answer
ansible-playbook site.yml --list-tasks --tags nginx
Scenario analysis
After the team upgraded from ansible-core 2.18 to 2.21, 30% of the nightly playbooks fail, with errors concentrated in Conditionals must have a boolean result; meanwhile someone reports that a config file fetched from an API now contains {{ env }} literals. Give a troubleshooting and fix plan.
Reference answer
① Both come from the 2.19 template engine changes: strict conditionals (#18) and template trust (#19). ② Short term: set allow_broken_conditionals only in affected projects as a temporary measure, and flag it. Long term: grep for when:.*{{, and change string/list conditions to | bool,| length > 0; ③ For the API config, do not render remote data a second time; instead pass the values as variables into a trusted template in the role's templates/; use _ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR=warning to find all occurrences; ④ Add a CI matrix test for new ansible-core versions, and run lint + Molecule before upgrading.
Teaching videos (titles and channels verified via YouTube oEmbed)
No verified video specifically covers the ansible-core 2.19 template engine changes; refer to the porting guide. Storyboard:
Visual: msg: {{ greeting }} An error with “missing quotes” highlighted. Narration: “YAML is parsed before Jinja2, so values starting with braces must be quoted.”
Visual: the priority ladder from Fig. 2-2, with role vars flashing. Narration: “Put tunable parameters in defaults, or inventory variables will always override them.”
Visual: Lab 2-C, the string "false" runs on the old version and errors on the new one. Narration: “2.19's strict conditionals are not trying to cause trouble; they are catching bugs that have been hiding for years.”
Official docs
Module 3 · Part A: Modules, idempotence and dependencies (Issues 26–38)
- Determine whether a Python dependency belongs on the control node (connection plugins, lookups, cloud modules running on localhost) or on the managed node (modules that execute remotely).
- Make a playbook truly idempotent: the second run reports
changed=0; understand when handlers are triggered and run. - Manage collection versions, FQCNs and deprecations, and read the failure output of modules
module_stderr. - Prerequisites:Lesson 1 Module 4 Idempotence,Lesson 2 Module 2 Collections; importance ★★★★☆.
Enter keywords (such as changed,Failed to import,couldn't resolve,handler,lock) to filter; click a row to jump to its details.
#26 Every PLAY RECAP shows changed=N: command/shell tasks always report changed
Symptom: There are no actual changes, yet the second and third runs still show changed; change auditing and drift detection lose their meaning, and handlers are triggered repeatedly, restarting services for no reason.
Root cause:command/shell/raw/script The module does not know what the command did, and reports changed: true whenever it runs. Other sources of non-idempotence: get_url Downloading to a temp name and then moving it, or a template containing ansible_date_time and similar values that change every time,lineinfile a regex that does not match (Issue 36).
Diagnostic commands
ansible-playbook site.yml --limit node1 && ansible-playbook site.yml --limit node1 | grep -E '^changed:|changed=' ansible-playbook site.yml --limit node1 --check --diff | grep -B2 -A10 '^changed'
changed: [node1] => (item=init database) node1 : ok=12 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Fix
# 1) prefer a dedicated module first (apt, user, postgresql_db, systemd …)
# 2) run only when needed
- name: Initialize database
ansible.builtin.command: /opt/myapp/bin/init-db
args:
creates: /var/lib/myapp/.initialized
# 3) read-only commands: never report changes
- name: Get app version
ansible.builtin.command: /opt/myapp/bin/myapp --version
register: app_ver
changed_when: false
check_mode: false # still runs in check mode (read-only, safe)
# 4) decide based on the output
- name: Enable feature flag
ansible.builtin.command: myappctl feature enable x
register: r
changed_when: "'already enabled' not in r.stdout"
Prevention and best practices
- In CI, run an idempotence test: Molecule's
idempotencestep runs a second time and fails on any change. - Enable the ansible-lint
no-changed-when,command-instead-of-modulerules.
#27 Failed to import the required Python library (botocore and boto3) on ctrl's Python /usr/bin/python3. Please read the module documentation and install it in the appropriate location.
Symptom: Running amazon.aws.ec2_instance,amazon.aws.aws_ec2 or an inventory plugin reports missing boto3; even though you have pip install boto3 installed it, it still errors. The message usually ends with a line: if the library is installed but Ansible uses the wrong interpreter, see the ansible_python_interpreter documentation. The Azure collection's equivalent is a missing azure SDK-related package.
Root cause: The path in the error message indicates which Python is missing the library. Cloud modules typically run on localhost : the implicit localhost uses the Python that runs ansible-playbook (pipx venv). In the inventory,explicitly sets to localhost ansible_connection=local , interpreter discovery finds the system Python (/usr/bin/python3), so the boto3 injected into the venv is not visible. Inventory plugins and lookups always run in Ansible's own Python.
Diagnostic commands
ansible --version | grep 'python version' # Ansible's own Python (venv) ansible localhost -m setup -a 'filter=ansible_python' | grep executable # Python the module uses on localhost pipx runpip ansible list 2>/dev/null | grep -iE 'boto3|botocore' grep -n localhost inventory* 2>/dev/null
python version = 3.12.3 (...) [GCC 13.2.0] (/home/andy/.local/share/pipx/venvs/ansible/bin/python)
"executable": "/usr/bin/python3", ← not the venv!
boto3 1.x.x
botocore 1.x.x
inventory.ini:1:localhost ansible_connection=local
Fix
pipx inject ansible boto3 botocore # install into Ansible's venv
# host_vars/localhost.yml — make modules on localhost use Ansible's own Python
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
or simply do not declare localhost in the inventory and use the implicit localhost.
Prevention and best practices
- Each collection declares its Python dependencies in
requirements.txt(ormeta/ee-requirements.txt); the EE installs them uniformly with ansible-builder (Issue 46). - The project README states which Python to install dependencies into; CI images and local environments use the same EE.
#28 Failed to import the required Python library (psycopg2) on db1's Python /usr/bin/python3.
Symptom:community.postgresql.postgresql_db / postgresql_user Fails on database hosts; on the control node, pip install psycopg2 has no effect.
Root cause: The opposite of issue 27: these modules run on the managed node (db1), where they connect to PostgreSQL locally, so the Python library must be installed in the Python that Ansible selects on db1. The message “on db1's Python /usr/bin/python3” states the location clearly. Newer versions of community.postgresql also support psycopg (v3); see the collection docs for the supported driver versions.
Diagnostic commands
ansible db1 -m command -a "/usr/bin/python3 -c 'import psycopg2; print(psycopg2.__version__)'" ansible db1 -m setup -a 'filter=ansible_python' | grep executable
db1 | FAILED | rc=1 >> ModuleNotFoundError: No module named 'psycopg2'
Fix
- name: Install PostgreSQL Python driver on the DB host
ansible.builtin.apt:
name: python3-psycopg2 # use the distro package to avoid pip install on the system Python (PEP 668)
state: present
become: true
- name: Create app database
community.postgresql.postgresql_db:
name: myapp
become: true
become_user: postgres # remember issue 10: needs acl or pipelining
Prevention and best practices
- Install the remote dependencies that the modules need in the role's first group of tasks (
python3-psycopg2,python3-docker,python3-pymysql…). - On Ubuntu 24.04, the system Python is protected by PEP 668, so it will report
pip installan errorexternally-managed-environment; use an apt package or a dedicated venv +ansible_python_interpreter.
See Lesson 6 Module 4.
#29 ERROR! couldn't resolve module/action 'community.docker.docker_container'. This often indicates a misspelling, missing collection, or incorrect module path.
Symptom: A playbook that runs locally fails at parse time in CI, AWX, or on a colleague's machine.
Root cause: The collection is not installed in the current environment's COLLECTIONS_PATHS path: only ansible-core was installed, not the community package; the EE image does not include the collection; the collection was installed to another user or path; or the module name is misspelled or has moved to another collection (Issue 30).
Diagnostic commands
ansible-galaxy collection list community.docker ansible-config dump | grep -E '^COLLECTIONS_PATHS' ansible-doc community.docker.docker_container | head -3
[WARNING]: - the configured path /home/runner/.ansible/collections does not exist. Unable to find collection community.docker ... (exact wording depends on actual output) COLLECTIONS_PATHS(default) = ['/home/runner/.ansible/collections', '/usr/share/ansible/collections']
Fix
# collections/requirements.yml (AWX installs dependencies from this path automatically)
collections:
- name: community.docker
version: ">=4.0.0,<5.0.0"
- name: community.postgresql
ansible-galaxy collection install -r collections/requirements.yml
Prevention and best practices
- Every project has a
collections/requirements.ymlpinned to major versions; CI and AWX use the same EE. - Within the project, the
ansible.cfgsetting can be set tocollections_path = ./collections:~/.ansible/collections, so dependencies travel with the project.
#30 [DEPRECATION WARNING] / ERROR! [DEPRECATED]: ansible.builtin.include has been removed. Use include_tasks or import_tasks instead. (module deprecations, renames and FQCN)
Symptom: After an upgrade, many deprecation warnings appear, or old syntax fails outright. Typical examples: include: has been removed from ansible-core (since 2.16); yum the module was removed in 2.17 and redirected to dnf; many short module names from the 2.9 era (such as docker_container,ec2) were moved, renamed or removed as collections were split.
Root cause: ansible-core only keeps ansible.builtin, while other modules evolve independently inside collections; major collection releases remove deprecated modules and parameters. Short names rely on a “routing redirect table” and collections: keyword resolution, which can resolve to different collections in different environments.
Diagnostic commands
ansible-playbook site.yml --syntax-check 2>&1 | grep -iE 'deprecat|removed' ansible-lint --profile production . | grep -E 'fqcn|deprecated-module|deprecated-local-action' ansible-doc -l community.general | wc -l
roles/app/tasks/main.yml:4: fqcn[action-core]: Use FQCN for builtin module actions (copy). roles/app/tasks/main.yml:9: deprecated-module: Deprecated module (...)
Fix
# before
- include: install.yml
- yum: name=httpd state=present
- docker_container: name=web image=nginx
# after
- ansible.builtin.import_tasks: install.yml
- ansible.builtin.dnf: { name: httpd, state: present }
- community.docker.docker_container: { name: web, image: nginx }
ansible-lint can automatically fix some of these issues: ansible-lint --fix (it rewrites files, so commit first, then run).
Prevention and best practices
- Use FQCN everywhere; in CI, treat deprecation warnings as technical debt that must be fixed (
ANSIBLE_DEPRECATION_WARNINGS=Trueand collect logs). - Before upgrading a major collection version, read its changelog's “Removed Features”.
#31 nginx.conf was changed but nginx was not restarted: handler not triggered / The requested handler 'Restart nginx' was not found in either the main handlers list nor in the listening handlers list
Symptom: The config file has been updated but the service still runs the old config; or parsing reports that a handler cannot be found.
Root cause:① notify The name does not match the handler's name/listen (case and spaces both matter); ② the task is ok rather than changed, and only changed results notify; ③ a notified handler whose later task fails: the host is removed from the play, and the handler does not run by default, so on the next run the file is already ok and no notification is sent, and the change is permanently “lost”; ④ handlers run only at the end of the play (or meta: flush_handlers), while the same play runs a health check right after that depends on the new config.
Diagnostic commands
grep -rnE 'notify:|listen:|- name:' roles/web/tasks roles/web/handlers | grep -iE 'notify|restart|listen' ansible-playbook site.yml --limit node1 -v | grep -E 'RUNNING HANDLER|NOTIFIED|changed:'
roles/web/tasks/main.yml:14: notify: Restart nginx roles/web/handlers/main.yml:1:- name: restart nginx ← case mismatch NOTIFIED HANDLER ... (with -v, notification info is shown; exact wording depends on actual output)
Fix
# handlers/main.yml: use listen to provide a stable “topic name”
- name: Restart nginx service
ansible.builtin.systemd: { name: nginx, state: restarted }
listen: web config changed
# tasks:
- ansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf, validate: "nginx -t -c %s" }
notify: web config changed
- ansible.builtin.meta: flush_handlers # when the change must take effect before later health checks
- ansible.builtin.uri: { url: "http://localhost/healthz" }
To prevent “lost restarts”: ansible-playbook --force-handlers or in play/ansible.cfg, set force_handlers: true, so notified handlers run even if later tasks fail.
Prevention and best practices
- For config files, use
validateto check before replacing, so handlers do not restart onto a broken config. - Normalize handler names (ansible-lint
name[casing]), and preferlisten.
#32 Failure in --check mode: 'dict object' has no attribute 'stdout' (the earlier command task was skipped in check mode)
Symptom: Normal runs are fine, but running with --check fails partway through; or check mode is “all green” while the real run fails.
Root cause: In check mode, modules that do not support check mode (and command/shell tasks without creates/removes ) are not executed and return skipped (the msg is like “Command would have run if not in check mode”; exact wording depends on version),register the result has no stdout, so later tasks that depend on it fail. Check mode is only a “prediction”: steps that depend on a real change from an earlier step (for example, configuring a service after installing its package) may report “service does not exist”.
Diagnostic commands
ansible-playbook site.yml --limit node1 --check -v 2>&1 | grep -B3 -E "skipping|has no attribute"
skipping: [node1] => {"changed": false, "msg": "Command would have run if not in check mode", "skipped": true}
fatal: [node1]: FAILED! => {"msg": "... 'dict object' has no attribute 'stdout' ..."}
Fix
# read-only probe commands: also run in check mode
- ansible.builtin.command: cat /etc/myapp/version
register: cur_ver
changed_when: false
check_mode: false
# steps that only make sense in a real run
- ansible.builtin.systemd: { name: myapp, state: started }
when: not ansible_check_mode
# defensive reference
- ansible.builtin.debug: { msg: "{{ cur_ver.stdout | default('unknown') }}" }
Prevention and best practices
- In CI, run each playbook once with
--check --diff, and treat “runs in check mode” as a quality gate (drift detection relies on it; Question 47). - In custom modules, declare
supports_check_mode=Trueand implement it correctly (Question 27).
See Lesson 2 Module 6.
#33 Failed to lock apt for exclusive operation: Failed to lock directory /var/lib/apt/lists/: E:Could not get lock /var/lib/apt/lists/lock. It is held by process 1234 (apt-get)
Symptom: The first apt task on a newly created cloud VM fails; it succeeds again after retrying for a few minutes.
Root cause: On first boot, Ubuntu's cloud-init and unattended-upgrades (the apt-daily timer) run apt in the background and hold the dpkg/apt lock. The apt module waits for a while by default (lock_timeout parameter, 60 seconds by default), and fails if the lock is still held after that.
Diagnostic commands
ansible newvm -b -m shell -a 'ps -eo pid,etime,cmd | grep -E "apt|dpkg|unattended" | grep -v grep; cloud-init status'
1234 02:31 /usr/bin/python3 /usr/bin/unattended-upgrade --download-only status: running
Fix
- name: Wait for cloud-init to finish
ansible.builtin.command: cloud-init status --wait
changed_when: false
- name: Install packages
ansible.builtin.apt:
name: [nginx, acl]
update_cache: true
cache_valid_time: 3600
lock_timeout: 600 # wait longer
register: apt_res
retries: 3
delay: 20
until: apt_res is succeeded
Prevention and best practices
- The first play on a new host should wait for cloud-init to finish; complete system upgrades in advance in the golden image.
- Do not “kill the apt process and delete the lock file”, which can corrupt the dpkg state.
#34 "msg": "No package matching 'nginx' is available"
Symptom: apt installs fail on containers or new images, even though the package names are correct.
Root cause: The apt index is empty or stale: many container image builds clean up rm -rf /var/lib/apt/lists/* (as this course's lab8-node does), and new machines may also never have apt update run; the other common cause is that required repositories (universe, third-party sources) are not enabled, or the architecture or release codename is wrong.
Diagnostic commands
ansible node1 -m shell -a 'ls /var/lib/apt/lists | wc -l; apt-cache policy nginx | head -3'
node1 | CHANGED | rc=0 >> 1 nginx: Installed: (none) Candidate: (none)
Fix
- ansible.builtin.apt:
name: nginx
update_cache: true
cache_valid_time: 3600 # do not update again within 1 hour, keeping it idempotent and fast
become: true
Add third-party sources with ansible.builtin.deb822_repository (the newer way) or apt_repository and distribute the signing key.
Prevention and best practices
- In the base role, at the start, run
update_cacheonce; later tasks should not repeat it. - In enterprise environments, use internal mirrors (Nexus/Artifactory/Pulp) to avoid dependence on the public internet and rate limits.
See Lesson 1 Module 3.
#35 System has not been booted with systemd as init system (PID 1). Can't operate. / Could not find the requested service nginx: host
Symptom: Running inside containers (such as this course's lab8-node, Docker/kind test environments, and some CI containers) ansible.builtin.systemd/service fails. It also occurs when systemd is not enabled in WSL.
Root cause: The container's PID 1 is the application process (here, sshd), with no systemd,systemctl so it cannot connect to the systemd bus. service After falling back to another service manager, the service definition is also not found.
Diagnostic commands
ansible node1 -m command -a 'ps -p 1 -o comm=' ansible node1 -m setup -a 'filter=ansible_service_mgr'
node1 | CHANGED | rc=0 >>
sshd
"ansible_service_mgr": "sshd" ← not systemd (the exact value depends on actual output)
Fix
- The test environment needs systemd: use Molecule with an image that includes systemd (such as a community-provided systemd image) and run it with privileged/cgroup mounts, or switch to VMs (multipass, Vagrant), or use Molecule's delegated driver with cloud VMs.
- Make the playbook container-compatible:
when: ansible_facts.service_mgr == 'systemd', in container scenarios, start the process directly or skip the task. - Production containers should not be managed by “using Ansible to manage services inside containers”; instead, build images (Docker course) or hand them to Kubernetes (Lesson 6 Module 7).
Prevention and best practices
- Define a clear test matrix: which roles are tested in containers and which must be tested in VMs.
- In WSL2, you can enable systemd in
/etc/wsl.confby setting[boot] systemd=true.
#36 lineinfile appends a line on every run: duplicate MaxConnections=200 appears in the config file
Symptom: Each run adds one more identical line at the end of the file; the task reports changed every time.
Root cause:lineinfile It uses regexp to find the line to replace; if regexp cannot match the modified line, so on the next run it cannot be found, and line is appended again. Typical mistake: regexp written as ^#MaxConnections (matches only comment lines); no regexp given, while line differs from the existing line by whitespace; if the file has several matches, only the last one is replaced.
Diagnostic commands
ansible node1 -b -m command -a 'grep -n MaxConnections /etc/myapp/app.conf' ansible-playbook site.yml --limit node1 --check --diff --tags config
12:#MaxConnections=100 40:MaxConnections=200 41:MaxConnections=200
Fix
- ansible.builtin.lineinfile:
path: /etc/myapp/app.conf
regexp: '^#?\s*MaxConnections\s*=' # matches both comment lines and already-modified lines
line: 'MaxConnections=200'
# multi-line config: use blockinfile (with markers); when you control the whole file, use template
Prevention and best practices
- Prefer
templateto manage the whole file;lineinfileis only suitable for changing individual lines in files owned by others. - For INI-style files, use
community.general.ini_file, and for structured files use the matching filter or module.
See Lesson 1 Module 7.
#37 "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "module_stderr": "Traceback (most recent call last): …" or "Killed"
Symptom: The module crashes with no structured error message; module_stderr is a Python traceback,Killed (remote out of memory) or blank,rc and the exit code may be 1, 137, etc.
Root cause: The module process exits abnormally before returning JSON: the remote side is missing a library, the module has a bug, the remote host ran out of memory (OOM), SELinux denied access, or non-JSON output was mixed into stdout (for example, a shell login script printing a welcome message in a non-interactive session, so Ansible cannot parse it).
Diagnostic commands
ansible node1 -m community.general.xxx -a '...' -vvv 2>&1 | sed -n '/module_stderr/,/rc/p' # keep the remote module file, then log in and run it manually ANSIBLE_KEEP_REMOTE_FILES=1 ansible node1 -m ansible.builtin.ping -vvv 2>&1 | grep -o '/home/ansible/.ansible/tmp/ansible-tmp-[^/ ]*' | head -1 ssh -p 2221 ansible@127.0.0.1 cd ~/.ansible/tmp/ansible-tmp-*/ && python3 AnsiballZ_ping.py explode && ls debug_dir python3 AnsiballZ_ping.py execute # shows the full exception directly
/home/ansible/.ansible/tmp/ansible-tmp-1731639600.12-4242-1234
Module expanded into:
/home/ansible/.ansible/tmp/ansible-tmp-.../debug_dir
{"ping": "pong", "invocation": {"module_args": {"data": "pong"}}}
Fix
- Fix based on the traceback: install the missing library, upgrade the collection version (check the issue tracker), or adjust remote memory.
- If a login script prints output, move the
.bashrcecho in it into[[ $- == *i* ]]an interactive-only check.
Prevention and best practices
- After debugging, delete the retained remote temp files, since they may contain secrets from module arguments.
- For modules with large output, watch remote memory; for very long tasks, use async (Issue 43).
#38 ERROR! Failed to resolve the requested dependencies map. Could not satisfy the following requirements: * community.general:>=10.0.0 (direct request) * community.general:<9.0.0 (dependency of acme.infra:1.4.2)
Symptom:ansible-galaxy collection install -r requirements.yml Installation fails; or it succeeds, but the collection version used at runtime is not the one you installed (new parameters are “not found”).
Root cause:① Version constraint conflicts: direct and transitive dependencies require incompatible ranges. ② the same collection exists in multiple paths: the community package ships its own copy in site-packages, and another copy is installed in ~/.ansible/collections , and there is one more in the project directory; Ansible uses the first match in COLLECTIONS_PATHS order.
Diagnostic commands
ansible-galaxy collection list community.general # list the versions in all paths ansible-galaxy collection install -r requirements.yml -vvv 2>&1 | grep -iE 'requirement|conflict' | head ansible-config dump | grep COLLECTIONS_PATHS
# /home/andy/proj/collections/ansible_collections Collection Version ----------------- ------- community.general 9.5.0 # /home/andy/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible_collections Collection Version ----------------- ------- community.general 11.x.x
Fix
- Conflict: upgrade or replace the internal collection with an overly strict constraint (
acme.infra), or choose a version in requirements that satisfies both. - Multiple paths: remove copies that should not exist; pin
collections_pathin the project, and when installing, use-p ./collections; to override when needed, use--forceor--upgrade.
Prevention and best practices
- Pin collection versions in the EE (ansible-builder), and use the same EE image digest locally, in CI and in AWX.
- Internal collections follow semantic versioning; do not hard-cap dependency ranges unless there is a real incompatibility.
- Consider using
ansible-galaxy collection verifyand signature verification to secure the supply chain (Question 48).
Decision tree for module failures and non-idempotent behavior
Enter from “error type” or “abnormal behavior”; each conclusion includes real diagnostic commands.
~/lab8/m3 , after running cp ../inventory.ini . .Lab 3-A: make a shell task idempotent (#26)
mkdir -p ~/lab8/m3 && cd ~/lab8/m3 && cp ../inventory.ini .
cat > idem.yml <<'EOF'
- hosts: node1
gather_facts: false
become: true
tasks:
- name: Init marker (non-idempotent)
ansible.builtin.shell: echo initialized >> /opt/lab8-init.log
- name: Read kernel version
ansible.builtin.command: uname -r
register: k
EOF
for i in 1 2; do ansible-playbook -i inventory.ini idem.yml | grep -E 'node1 +:'; donenode1 : ok=2 changed=2 unreachable=0 failed=0 ... node1 : ok=2 changed=2 unreachable=0 failed=0 ...
cat > idem.yml <<'EOF'
- hosts: node1
gather_facts: false
become: true
tasks:
- name: Init marker (idempotent)
ansible.builtin.shell: echo initialized >> /opt/lab8-init.log
args:
creates: /opt/lab8-init.log
- name: Read kernel version
ansible.builtin.command: uname -r
register: k
changed_when: false
check_mode: false
EOF
ansible node1 -b -m file -a 'path=/opt/lab8-init.log state=absent' >/dev/null
for i in 1 2; do ansible-playbook -i inventory.ini idem.yml | grep -E 'node1 +:'; donenode1 : ok=2 changed=1 unreachable=0 failed=0 ... node1 : ok=2 changed=0 unreachable=0 failed=0 ...
ansible node1 -b -m file -a 'path=/opt/lab8-init.log state=absent'Lab 3-B: “lost restart” and --force-handlers (#31)
cat > handler.yml <<'EOF'
- hosts: node1
gather_facts: false
become: true
vars: { conf_version: 1 }
tasks:
- name: Deploy config
ansible.builtin.copy:
content: "version={{ conf_version }}\n"
dest: /etc/lab8-app.conf
notify: Restart app
- name: A later task fails
ansible.builtin.command: /bin/false
handlers:
- name: Restart app
ansible.builtin.shell: date >> /tmp/lab8-restarts.log
EOF
ansible-playbook -i inventory.ini handler.yml -e conf_version=2 | grep -E 'changed:|fatal|HANDLER'
ansible node1 -m command -a 'cat /tmp/lab8-restarts.log'changed: [node1]
fatal: [node1]: FAILED! => {"changed": true, "cmd": ["/bin/false"], ... "rc": 1}
node1 | FAILED | rc=1 >>
cat: /tmp/lab8-restarts.log: No such file or directory ← handler did not runansible-playbook -i inventory.ini handler.yml -e conf_version=2 | grep -E 'ok: \[node1\]|HANDLER'
ok: [node1] ← config unchanged → never restarts
--force-handlers :ansible-playbook -i inventory.ini handler.yml -e conf_version=3 --force-handlers | grep -E 'HANDLER|changed:' ansible node1 -m command -a 'cat /tmp/lab8-restarts.log'
changed: [node1] RUNNING HANDLER [Restart app] *** changed: [node1] node1 | CHANGED | rc=0 >> Fri Nov 15 03:00:00 UTC 2026
ansible node1 -b -m shell -a 'rm -f /etc/lab8-app.conf /tmp/lab8-restarts.log'Lab 3-C: lineinfile duplicate appends (#36) and systemd in containers (#35)
ansible node1 -b -m copy -a 'dest=/tmp/lab8.conf content="#MaxConnections=100\n"' for i in 1 2 3; do ansible node1 -b -m lineinfile -a "path=/tmp/lab8.conf regexp='^#MaxConnections' line='MaxConnections=200'" -o | cut -c1-40; done ansible node1 -m command -a 'cat /tmp/lab8.conf'
node1 | CHANGED => {"backup": "","chan
node1 | CHANGED => {"backup": "","chan
node1 | CHANGED => {"backup": "","chan
MaxConnections=200
MaxConnections=200
MaxConnections=200The first run replaced the comment line; afterwards regexp matches only the comment line, so when nothing is found it appends.
ansible node1 -b -m copy -a 'dest=/tmp/lab8.conf content="#MaxConnections=100\n"' >/dev/null for i in 1 2 3; do ansible node1 -b -m lineinfile -a "path=/tmp/lab8.conf regexp='^#?\s*MaxConnections\s*=' line='MaxConnections=200'" -o | cut -c1-30; done
node1 | CHANGED => {"backup"
node1 | SUCCESS => {"backup"
node1 | SUCCESS => {"backup"ansible node1 -b -m ansible.builtin.systemd -a 'name=ssh state=restarted'
node1 | FAILED! => { ... "System has not been booted with systemd as init system (PID 1). Can't operate." ... } (exact wording depends on actual output)ansible node1 -b -m file -a 'path=/tmp/lab8.conf state=absent'; rm -rf ~/lab8/m3Command questions
1. Check how many copies of community.general exist in the current environment, and which paths they are in.
Reference answer
ansible-galaxy collection list community.general ansible-config dump | grep COLLECTIONS_PATHS
2. Keep the remote module file and run it manually to see the full exception of the module.
Reference answer
ANSIBLE_KEEP_REMOTE_FILES=1 ansible node1 -m ansible.builtin.ping -vvv # log in to node1, then go to ~/.ansible/tmp/ansible-tmp-*/ python3 AnsiballZ_ping.py explode && python3 AnsiballZ_ping.py execute
Scenario analysis
A playbook creates EC2 in an AWS account and configures PostgreSQL. It works locally, but in CI, amazon.aws.ec2_instance reports a missing boto3; after fixing that, postgresql_user it reports a missing psycopg2. The CI maintainer ran pip install boto3 psycopg2-binary on the runner, but the problem persists. Analyze the cause and give a long-term plan.
Reference answer
boto3 must be installed in the Python used by localhost for running the ec2 module (usually Ansible's venv, or the system Python discovered when localhost is declared explicitly, #27); psycopg2 must be installed on the database host rather than the runner (#28); installing both with pip on the runner is wrong. Long term: build an EE (ansible-builder) that includes ansible-core, amazon.aws, community.postgresql and their Python dependencies, and use the same EE in CI and AWX; have the database role install python3-psycopg2 as its first step; explicitly set localhost ansible_python_interpreter: "{{ ansible_playbook_python }}".
Teaching video (title and channel verified via YouTube oEmbed)
No verified video was found that specifically covers troubleshooting module dependencies and idempotence. Storyboard:
Visual: the same playbook run twice in a row; the second run still shows changed=2. Narration: “command and shell do not know what they did, so they always say changed.”
Visual: Fig. 3-1 in two columns, boto3 flies to the left, psycopg2 flies to the right. Narration: “Whichever machine and Python the error names, that is where you install it.”
Visual: Lab 3-B, a handler swallowed by a failed task, then recovered after --force-handlers. Narration: “In production, this means the config changed but the service was never restarted.”
Official docs
Module 4 · Part A: Scale, performance, platforms and CI (Issues 39–50)
- Use
profile_tasks/timercallbacks to measure where the slowness is, and optimize in the order “connection → facts → task count → concurrency”. - Identify control-node resource issues (memory, file descriptors) and connection limits on managed nodes and jump hosts.
- Troubleshoot problems that “only fail in AWX / EE / CI”: dependencies, credentials, Vault password, config file loading, locale.
- Prerequisites:Lesson 7 Module 4 Performance,Lesson 5 Module 2 CI,Module 4 AWX; importance ★★★★☆.
Enter keywords (such as forks,dead state,No inventory,vault,world writable,UTF-8) to filter; click a row to jump to its details.
#39 Running the site playbook across 1500 hosts takes 3 hours (slow at large scale)
Symptom: As the number of hosts grows, run time grows linearly or even faster; most of the time it appears to “hang” at the start of each task.
Root cause: Default forks = 5: with the linear strategy, each task runs on only 5 hosts in parallel at a time; each task goes through several round trips (SSH connection setup if not reused, creating a temp directory, transfer, execution, cleanup); each host gathers full facts; and modules are called item by item inside loops (for example, apt a loop of 30 packages = 30 round trips).
Diagnostic commands
ansible-config dump --only-changed | grep -E 'FORKS|PIPELINING|SSH_ARGS|GATHERING|CALLBACKS' ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer ansible-playbook site.yml --limit 'web[0:49]' | tail -25
DEFAULT_FORKS(default) = 5 Gathering Facts ------------------- 312.40s common : Install base packages ---- 288.11s nginx : Template site config ------ 95.32s Playbook run took 0 days, 0 hours, 14 minutes, 2 seconds
Fix
[defaults] forks = 50 # raise gradually based on control-node CPU/memory (Issue 41) gathering = smart # use together with fact caching fact_caching = ansible.builtin.jsonfile fact_caching_connection = ~/.cache/ansible-facts fact_caching_timeout = 86400 [ssh_connection] pipelining = True # first confirm there is no requiretty (Issue 7) ssh_args = -o ControlMaster=auto -o ControlPersist=60s
# pass the list to the module once, instead of using loop
- ansible.builtin.apt: { name: "{{ base_packages }}", state: present }
# when hosts have no dependencies between them, the free strategy lets fast hosts skip waiting for slow ones
- hosts: web
strategy: free
Prevention and best practices
- For key playbooks, keep recording run time (AWX job duration, CI metrics), and alert on regressions.
- At very large scale, consider sharding (run several jobs in parallel by region or group, AWX job slicing) or ansible-pull pull mode (Question 46).
- Check the compatibility of third-party accelerators (such as Mitogen) with newer ansible-core yourself; do not rely on them by default in production.
#40 Gathering Facts hangs for minutes / reports timeout (unresponsive NFS mount, slow hardware info collection)
Symptom: Some hosts stay in the Gathering Facts stage for a long time, and finally show timeout-related warnings or failures (for example, timing out while getting mount information; the wording varies by version), slowing down the whole batch.
Root cause:setup The module gathers several subsets by default; the hardware subset walks the mount points and runs statvfs, and when it hits an unresponsive NFS/CIFS mount it blocks; some virtualization platforms read DMI information very slowly; gather_timeout (default 10 seconds) sets the timeout for each individual collection step.
Diagnostic commands
time ansible slowhost -m setup -a 'gather_subset=!all,!min,network' -o >/dev/null # collect only network facts time ansible slowhost -m setup -a 'gather_subset=hardware' >/dev/null ansible slowhost -b -m shell -a 'timeout 5 df -h || echo "df hung"; grep -E "nfs|cifs" /proc/mounts'
real 0m1.9s real 1m40.3s df hung nas01:/export/data /mnt/data nfs4 rw,relatime,hard ...
Fix
- hosts: all gather_facts: true gather_subset: ['!hardware', 'network', 'virtual'] # collect only what is needed gather_timeout: 20 # or in ansible.cfg: gathering = smart + fact cache
Root fix: repair or unmount the broken network mount (changing mount options such as soft,x-systemd.automount etc. should be evaluated with the storage team).
Prevention and best practices
- Most playbooks only use network and distribution information; by default, at the play level, narrow
gather_subset. - Plays that do not need facts should always set
gather_facts: false.
#41 ERROR! A worker was found in a dead state (control node out of memory)
Symptom: During large runs, ansible-playbook suddenly aborts with a worker in dead state; the kernel log of the control node (or the AWX execution node / EE container) shows OOM killer records; the AWX job status is Error.
Root cause: Each fork is a separate worker process that holds copies of host variables, task results and so on. forks Forks set very high + a large inventory (many hostvars) + tasks returning huge results (for example, register reads the whole log file,find returns tens of thousands of files,slurp on large files) → memory multiplies. Containers (EE) with memory limits make this easier to trigger.
Diagnostic commands
sudo dmesg -T | grep -iE 'killed process|out of memory' | tail -3 /usr/bin/time -v ansible-playbook site.yml --limit 'web[0:99]' 2>&1 | grep -E 'Maximum resident' grep -rnE 'register:|slurp|find:' roles/ | head
[Fri Nov 15 03:00:00 2026] Out of memory: Killed process 4242 (ansible-playboo) total-vm:2.1GB ... Maximum resident set size (kbytes): 1843200
Fix
- Count forks by memory: first lower them to a value that runs stably, then raise them gradually; in AWX, adjust the instance forks/capacity and container group resource requests.
- Avoid registering large results: keep only the fields you need (
command: wc -l fileinstead ofslurp),loop_control: labelreduce output; for large files, usefetchinstead of reading them into a variable. - Split runs (
serial, split jobs by group).
Prevention and best practices
- Set memory monitoring and alerts on control/execution nodes; in CI, use
/usr/bin/time -vto record peak memory. - A dynamic inventory should fetch only the host variables it needs (
compose/keyed_groupskeep it lean, instead of importing all tags).
#42 After raising forks, some hosts randomly become UNREACHABLE: kex_exchange_identification: read: Connection reset by peer
Symptom: After raising forks from 5 to 100, a random batch of hosts becomes UNREACHABLE on each run; a rerun succeeds; it is especially noticeable when connecting through a jump host.
Root cause: The OpenSSH server's MaxStartups (default 10:30:100) limits “concurrent connections that have not yet completed authentication”: beyond 10, they start being dropped probabilistically. When connecting through the same jump host, every connection must first handshake on the jump host; without ControlPersist reuse, each task may open new connections. In addition, a low file descriptor limit on the control node (ulimit -n) can also cause connection failures.
Diagnostic commands
ansible-playbook site.yml -f 100 2>&1 | grep -c 'kex_exchange_identification' ssh bastion 'sudo sshd -T | grep -i maxstartups; sudo journalctl -u ssh --since -10m | grep -c "beginning MaxStartups throttling"' ulimit -n
17 maxstartups 10:30:100 42 1024
Fix
- Jump host: increase
MaxStartups(for example100:30:200) andMaxSessions, and make sure resources are sufficient. - Control node: enable ControlPersist to reuse connections; raise the file descriptor limit
ulimit -n 65536(set at the service or container level in systemd/AWX). - Ansible: set
forksto match jump-host capacity; for connection-type failures, combine it withretries(the ssh connection plugin'sreconnection_retriesoption, see the docs).
Prevention and best practices
- Capacity planning: the jump host is a single point of failure and a bottleneck; scale it horizontally or switch to managed channels such as SSM or Azure Bastion.
- For time-sensitive jobs, roll out gradually: first set
-f 20, then observe the jump-host metrics and raise it.
#43 Long task disconnects midway: Shared connection to 10.0.1.4 closed. / UNREACHABLE after upgrade or reboot
Symptom:apt dist-upgrade, database migrations, large archive extraction and other tasks that take over ten minutes fail midway; or a task after shell: reboot reports UNREACHABLE.
Root cause: The SSH session stays open while the task runs; idle timeouts on NAT, load balancers or firewalls along the path (commonly 4–15 minutes in the cloud) silently drop long connections that carry no data; a reboot always breaks the connection.
Diagnostic commands
ansible-playbook upgrade.yml --limit web1 -vvvv 2>&1 | grep -E 'Shared connection|Timeout|closed' | tail ansible-config dump | grep -E 'SSH_ARGS|TIMEOUT'
Fix
# Long tasks: run async and poll (each poll is a short connection)
- name: Full upgrade
ansible.builtin.apt: { upgrade: dist, update_cache: true }
async: 3600 # Run for up to 1 hour
poll: 30 # Check every 30 seconds
# Reboot: use the reboot module, which waits for the host to come back and verifies it
- ansible.builtin.reboot:
reboot_timeout: 900
test_command: uptime
[ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o ServerAliveInterval=30 -o ServerAliveCountMax=10
Prevention and best practices
- Use async for any task that may run longer than a few minutes; fire-and-forget (
poll: 0) withasync_statuscollect results (since 2.19, useis finishedto test). - Don't use
shell: reboot.
See Lesson 7 Module 5.
#44 [WARNING]: Unable to parse /home/andy/proj/inventory/ec2.yml as an inventory source / [WARNING]: No inventory was parsed, only implicit localhost is available
Symptom: Using amazon.aws.aws_ec2 or azure.azcollection.azure_rm inventory,ansible-inventory --graph is empty, and the playbook prints “provided hosts list is empty, only localhost is available”.
Root cause:① The inventory plugin requires the file name: aws_ec2 must end with aws_ec2.yml/aws_ec2.yaml , and azure_rm must end with azure_rm.yml/azure_rm.yaml ,ec2.yml is not recognized; ② plugin: is not a valid FQCN; ③ missing boto3/azure SDK (Issue 27; the inventory plugin runs in ansible's own Python); ④ wrong credentials/region or overly strict filters leave the result empty; ⑤ you set enable_plugins but did not list that plugin. The default warning is terse; check -vvv.
Diagnostic commands
ansible-inventory -i inventory/ec2.yml --graph -vvv 2>&1 | grep -iE 'failed to parse|plugin|boto|credentials' | head ansible-config dump | grep -E '^INVENTORY_ENABLED' aws sts get-caller-identity; aws ec2 describe-instances --region ca-central-1 --query 'length(Reservations)'
[WARNING]: * Failed to parse /home/andy/proj/inventory/ec2.yml with auto plugin: ... aws_ec2 ... does not end with aws_ec2.(yml|yaml) ... (exact wording depends on actual output) INVENTORY_ENABLED(default) = ['host_list', 'script', 'auto', 'yaml', 'ini', 'toml']
Fix
# inventory/prod.aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [ca-central-1]
filters:
tag:Env: prod
instance-state-name: running
keyed_groups:
- key: tags.Role
prefix: role
hostnames: [private-ip-address]
compose:
ansible_host: private_ip_address
Prevention and best practices
- Add a CI step that runs
ansible-inventory --graphand assert key groups are non-empty to prevent a false green “ran successfully on zero hosts”. - In the playbook, assert on the target group:
groups['role_web'] | length > 0.
#45 AWX/AAP job failed: ERROR! the role 'geerlingguy.docker' was not found in /runner/project/roles:… (works locally)
Symptom: The same repo works locally, but the job fails in AWX: role not found, collection not found (the Issue 29 error), vars file not found; or the project sync (Project Update) itself fails.
Root cause: AWX checks out the project to the EE container's /runner/project,only installs dependencies from the project-root roles/requirements.yml and collections/requirements.yml ; the repo-root requirements.yml, and the dev machine's ~/.ansible roles are invisible. A private Automation Hub / Galaxy also needs Galaxy credentials configured on the Organization. Selecting the wrong project branch or subdirectory (playbook path) is also common.
Diagnostic commands
# Local simulation of AWX's clean environment: run from scratch in the EE ansible-navigator run site.yml --eei registry.example.com/ee/infra:1.4 --mode stdout -i inventories/staging ls roles/requirements.yml collections/requirements.yml # On the AWX side: check the Project Update job output for the "ansible-galaxy role/collection install" step
ls: cannot access 'roles/requirements.yml': No such file or directory ls: cannot access 'collections/requirements.yml': No such file or directory
Fix
mkdir -p roles collections
git mv requirements.yml collections/requirements.yml # Collection dependencies
cat > roles/requirements.yml <<'EOF'
roles:
- name: geerlingguy.docker
version: "7.4.1" # Example version, pin to the actual one
EOF
Private source: add Galaxy/Automation Hub credentials in the AWX organization settings and order them; or build the dependencies directly into the EE (recommended for production, Issue 46).
Prevention and best practices
- “If it cannot run from a clean checkout in ansible-navigator with the same EE, do not push it to AWX”—put this step in CI.
- Pin role/collection versions; set a cache timeout on project sync to avoid installing from the network every time.
#46 Execution environment (EE) missing dependencies: Failed to import the required Python library (azure-…) on localhost's Python /usr/bin/python3 — only appears in AWX / navigator
Symptom: The local pipx environment runs fine, but fails in AWX or ansible-navigator : missing Python libraries, missing system commands (git,rsync,kubectl,session-manager-plugin), missing collections.
Root cause: An EE is a container image that contains ansible-core, collections, Python dependencies and system packages; jobs can only use what the image contains. The generic “Minimal/Supported EE” does not include your cloud SDK or specific CLIs.
Diagnostic commands
ansible-navigator images --mode stdout # List local EE images ansible-navigator exec --eei registry.example.com/ee/infra:1.4 -- ansible-galaxy collection list ansible-navigator exec --eei registry.example.com/ee/infra:1.4 -- python3 -m pip list | grep -i azure ansible-navigator exec --eei registry.example.com/ee/infra:1.4 -- which session-manager-plugin
Fix
# execution-environment.yml (ansible-builder format, version 3)
version: 3
images:
base_image:
name: quay.io/fedora/fedora:latest # Example; in production, use an organization-approved base image
dependencies:
ansible_core:
package_pip: ansible-core>=2.21,<2.22
ansible_runner:
package_pip: ansible-runner
galaxy: requirements.yml # Collections (reads the Python/system dependencies declared by the collection)
python: requirements.txt # Extra Python libraries
system: bindep.txt # System packages (git, openssh-clients …)
ansible-builder build -t registry.example.com/ee/infra:1.5 -f execution-environment.yml podman push registry.example.com/ee/infra:1.5
Check the official ansible-builder documentation for base images and fields.
Prevention and best practices
- An EE is code too: keep it in Git, have CI build and scan it, and publish it with version tags; AWX job templates should reference a pinned tag or digest.
- Use navigator with the same EE for local development too, eliminating “it works on my machine”.
See Lesson 2 Module 8.
#47 ERROR! Attempting to decrypt but no vault secrets found / Decryption failed (no vault secrets were found that could decrypt) on group_vars/prod/vault.yml
Symptom: The CI run fails. Case 1: no Vault password is provided at all. Case 2: a password is provided, but it is not the one used to encrypt this file (or the vault-id label does not match).
Root cause: CI is non-interactive, so --ask-vault-pass is unavailable; the developer's local vault_password_file points to a file that doesn't exist on the runner; multiple environments use different passwords but CI only provides one; someone used a new password to rekey part of the files.
Diagnostic commands
head -1 group_vars/prod/vault.yml # Check the format and vault-id label ansible-config dump --only-changed | grep -i vault ansible-vault view --vault-id prod@.vault_pass_prod group_vars/prod/vault.yml >/dev/null && echo OK
$ANSIBLE_VAULT;1.2;AES256;prod ← format 1.2 with label prod DEFAULT_VAULT_PASSWORD_FILE(/home/andy/proj/ansible.cfg) = /home/andy/.vault_pass ← does not exist on the runner
Fix
# GitHub Actions snippet: write the secret to a temp file, delete it after use
- name: Run playbook
env:
VAULT_PASS_PROD: ${{ secrets.VAULT_PASS_PROD }}
run: |
umask 077
printf '%s' "$VAULT_PASS_PROD" > "$RUNNER_TEMP/vault_prod"
ansible-playbook -i inventories/prod site.yml --vault-id "prod@$RUNNER_TEMP/vault_prod"
rm -f "$RUNNER_TEMP/vault_prod"
Multiple environments: one vault-id per environment (--vault-id dev@… --vault-id prod@…), and explicitly pass --encrypt-vault-id prod. You can also use an executable “client script” as the password source, reading from HashiCorp Vault / Key Vault (the script name must end with -client to be treated as a vault-id client; see the official docs).
Prevention and best practices
- Don't hardcode a personal path in the repo's ansible.cfg for
vault_password_file. - Going further: keep secrets out of the repo and look them up at runtime from an external secret system (Lesson 3 Key Vault, Lesson 4 Secrets Manager, Question 40); use the Vault credential type in AWX.
- Add
no_log: trueto sensitive tasks, so CI logs do not leak decrypted values.
#48 ansible-lint suddenly fails in CI: fqcn[action-core], name[missing], yaml[truthy], no-changed-when … (code unchanged)
Symptom: The lint step that passed yesterday fails today with a flood of new rule violations, or the Molecule idempotence step reports CRITICAL Idempotence test failed because of the following tasks.
Root cause: In CI, pip install ansible-lint is not version-pinned; a newer version added or tightened rules, or the default profile changed. A Molecule idempotence failure means that a non-idempotent task from Issue 26/36 was caught by the test, which is a good thing.
Diagnostic commands
ansible-lint --version
ansible-lint --profile production -f pep8 . | awk -F: '{print $4}' | sort | uniq -c | sort -rn | head
cat .ansible-lint 2>/dev/null || echo "No config file"
38 fqcn[action-core] 12 name[missing] 7 yaml[truthy] 3 no-changed-when No config file
Fix
# .ansible-lint (commit to the repo) profile: production # min → basic → moderate → safety → shared → production exclude_paths: - collections/ warn_list: # Temporarily downgrade to warnings; fix on a deadline - yaml[line-length] skip_list: []
Pin the version (ansible-lint==X.Y.Z ) or use a fixed version of the official GitHub Action; upgrade in a separate PR; fix auto-fixable issues first with ansible-lint --fix (review the diff before committing).
Prevention and best practices
- Run the same lint version locally with pre-commit; have Renovate/Dependabot submit lint upgrade PRs automatically.
- Keep the Molecule pipeline
idempotencestep; do not delete it just to make it pass.
#49 [WARNING]: Ansible is being run in a world writable directory (/builds/infra/ansible), ignoring it as an ansible.cfg source.
Symptom: When running in GitLab CI, in a Docker-mounted directory, or under WSL's /mnt/c , the project's ansible.cfg is ignored: roles_path, collections_path, forks and vault settings all revert to defaults, followed by a chain of errors such as role not found and collection not found.
Root cause: Security mechanism: if the current directory is writable by all users, anyone could drop a malicious ansible.cfg (for example one that specifies a plugin path to run arbitrary code), so Ansible refuses to load configuration from such a directory. CI runner checkout directories and Windows filesystem mounts are often set to 777 permissions.
Diagnostic commands
stat -c '%A %n' . ansible --version | grep 'config file'
drwxrwxrwx . config file = None
Fix
chmod o-w . # At the start of the CI script # Or explicitly specify the config file (not affected by directory permission checks) export ANSIBLE_CONFIG="$CI_PROJECT_DIR/ansible.cfg" ansible --version | grep 'config file'
config file = /builds/infra/ansible/ansible.cfg
Prevention and best practices
- Have the first CI step print
ansible --versionandansible-config dump --only-changed, so the configuration source is obvious at a glance. - In WSL, keep the project on the Linux filesystem (
~/) rather than/mnt/c.
#50 ERROR: Ansible requires the locale encoding to be UTF-8; Detected ISO8859-1.
Symptom: In slim CI containers, under cron, or in some SSH sessions, any ansible command fails immediately. The value after Detected depends on the environment (such as ISO8859-1,ANSI_X3.4-1968 etc.; follow the actual output).
Root cause: Newer ansible-core requires the control node's locale encoding to be UTF-8, so that file names, output and template encoding stay consistent; the environment variables LANG/LC_ALL are unset or point to a non-UTF-8 locale, and Ansible refuses to run.
Diagnostic commands
locale; python3 -c 'import locale; print(locale.getpreferredencoding())' locale -a | grep -i utf
LANG= LC_ALL= ANSI_X3.4-1968 C.utf8
Fix
export LANG=C.UTF-8 LC_ALL=C.UTF-8 # CI environment variables / Dockerfile ENV / top of the cron file
Prevention and best practices
- Bake into the EE / CI image
ENV LANG=C.UTF-8. - For ansible tasks scheduled by systemd timer / cron, explicitly set the environment variables (cron does not inherit the login shell's locale).
See Lesson 5 Module 7.
Scale, platform and CI troubleshooting decision tree
Distinguish three paths: “slow / dies midway / fails only on the platform or in CI”.
~/lab8/m4 directory. Three containers is a very small scale; Lab 4-A is about learning the measurement method, so the absolute numbers are not representative.Lab 4-A: measure the effect of forks and pipelining (#39)
mkdir -p ~/lab8/m4 && cd ~/lab8/m4 && cp ../inventory.ini .
cat > perf.yml <<'EOF'
- hosts: all
gather_facts: true
tasks:
- ansible.builtin.command: "true"
changed_when: false
loop: "{{ range(10) | list }}"
EOF
export ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer
ANSIBLE_FORKS=1 ANSIBLE_PIPELINING=0 ansible-playbook -i inventory.ini perf.yml | grep -E 'Playbook run took'
ANSIBLE_FORKS=10 ANSIBLE_PIPELINING=0 ansible-playbook -i inventory.ini perf.yml | grep -E 'Playbook run took'
ANSIBLE_FORKS=10 ANSIBLE_PIPELINING=1 ansible-playbook -i inventory.ini perf.yml | grep -E 'Playbook run took'Playbook run took 0 days, 0 hours, 0 minutes, 21 seconds Playbook run took 0 days, 0 hours, 0 minutes, 8 seconds Playbook run took 0 days, 0 hours, 0 minutes, 4 seconds
ANSIBLE_PIPELINING=0 ansible node1 -m ping -vvv 2>&1 | grep -c 'SSH: EXEC' ANSIBLE_PIPELINING=1 ansible node1 -m ping -vvv 2>&1 | grep -c 'SSH: EXEC'
3 ← mkdir temp dir / transfer / execute and clean up (exact count varies by version) 1
unset ANSIBLE_CALLBACKS_ENABLEDLab 4-B: world-writable directory and locale (#49, #50)
mkdir -p ~/lab8/m4/ww && cd ~/lab8/m4/ww printf '[defaults]\nforks = 42\n' > ansible.cfg chmod 777 . ansible-config dump --only-changed 2>&1 | head -3
[WARNING]: Ansible is being run in a world writable directory (/home/andy/lab8/m4/ww), ignoring it as an ansible.cfg source. For more information see https://docs.ansible.com/... (no DEFAULT_FORKS line: the config is ignored)
ANSIBLE_CONFIG=$PWD/ansible.cfg ansible-config dump --only-changed | grep FORKS chmod 755 . && ansible-config dump --only-changed | grep FORKS
DEFAULT_FORKS(/home/andy/lab8/m4/ww/ansible.cfg) = 42 DEFAULT_FORKS(/home/andy/lab8/m4/ww/ansible.cfg) = 42
env -i PATH="$PATH" HOME="$HOME" LANG=C LC_ALL=C ansible --version 2>&1 | head -2 env -i PATH="$PATH" HOME="$HOME" LANG=C.UTF-8 ansible --version | head -1
ERROR: Ansible requires the locale encoding to be UTF-8; Detected ANSI_X3.4-1968. ansible [core 2.21.x]
In Python 3.7+, C locale is sometimes forced to UTF-8 automatically (PEP 538), so the first command may also succeed on some systems; you can instead use LC_ALL=en_US.ISO-8859-1 (the locale must already be generated) to reproduce.
rm -rf ~/lab8/m4/wwLab 4-C: Vault password in CI (#47)
cd ~/lab8/m4 && mkdir -p group_vars/all echo 'dev-pass' > .vp_dev && echo 'prod-pass' > .vp_prod && chmod 600 .vp_* printf 'db_password: s3cr3t-prod\n' > group_vars/all/vault.yml ansible-vault encrypt --vault-id prod@.vp_prod group_vars/all/vault.yml head -1 group_vars/all/vault.yml
Encryption successful $ANSIBLE_VAULT;1.2;AES256;prod
ansible node1 -i inventory.ini -m debug -a var=db_password 2>&1 | tail -1 ansible node1 -i inventory.ini -m debug -a var=db_password --vault-id dev@.vp_dev 2>&1 | tail -1
ERROR! Attempting to decrypt but no vault secrets found ERROR! Decryption failed (no vault secrets were found that could decrypt) on /home/andy/lab8/m4/group_vars/all/vault.yml
export VAULT_PASS_PROD=prod-pass umask 077; printf '%s' "$VAULT_PASS_PROD" > /tmp/vp_prod ansible node1 -i inventory.ini -m debug -a var=db_password --vault-id dev@.vp_dev --vault-id prod@/tmp/vp_prod rm -f /tmp/vp_prod
node1 | SUCCESS => {
"db_password": "s3cr3t-prod"
}rm -rf ~/lab8/m4; unset VAULT_PASS_PRODCommand questions
1. Find the 10 most time-consuming tasks in a playbook.
Reference answer
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks ansible-playbook site.yml | tail -15
2. In CI, verify that the dynamic inventory actually returns web hosts, and fail the pipeline otherwise.
Reference answer
n=$(ansible-inventory -i inventory/prod.aws_ec2.yml --list | jq '.role_web.hosts | length')
test "${n:-0}" -gt 0 || { echo "role_web is empty"; exit 1; }Scenario analysis question
The platform team raised AWX job template forks from 10 to 200, hoping to cut the patching job for 2,000 hosts from 4 hours to 30 minutes. Instead the job often ends in Error, with “A worker was found in a dead state” in the logs, and some hosts report kex_exchange_identification. Give your analysis and a remediation plan.
Reference answer
Two bottlenecks: ① execution node / EE container memory is insufficient (#41), and the number of forks scales roughly linearly with memory; ② all connections go through the jump host and exceed sshd MaxStartups (#42). Remediation: size forks by memory (for example, 100 MB per fork plus headroom); use AWX job slicing to spread the job across several execution nodes; raise MaxStartups on the jump host and scale it horizontally, or switch to a managed channel such as SSM; enable ControlPersist + pipelining to reduce connection count; use async for the patching tasks; for a region-by-region rollout, use serial to roll in batches and set max_fail_percentage; measure with profile_tasks and iterate.
Teaching videos (titles and channels verified via YouTube oEmbed)
No verified video specifically on Ansible performance tuning or execution environment troubleshooting was found. Storyboard:
Visual: profile_tasks output, with Gathering Facts at the top. Narration: “Measure first. The default of five forks and collecting all facts on every host are the two most common wastes.”
Visual: Figure 4-2 three-column comparison, local → CI → AWX, with differences highlighted one by one. Narration: “When it fails on the platform, first look for environment differences: configuration, dependencies, credentials, locale.”
Visual: Lab 4-C, the two Vault errors and the vault-id fix. Narration: “no vault secrets found means no password was given; Decryption failed means the wrong password was given.”
Official docs
Module 5 · Part B: Core concepts and architecture (Questions 1–13)
- Explain how Ansible works using the chain “control node rendering → AnsiballZ → SSH → remote Python → JSON”.
- Explain how ansible-core, the Ansible community package, AWX and AAP relate, and how the positioning differs from Terraform, Puppet, Chef and Salt.
- Answer common follow-ups on inventory, connection plugins, facts, strategy, become and configuration precedence.
Skim the questions and focus areas first, and mark the ones you are unsure about; click a row to jump to the details.
Q1. What is Ansible? What do “agentless” and “push model” mean?Beginner
30-second answer
Ansible is a configuration management, application deployment and orchestration tool that describes the desired state in YAML. Agentless: managed nodes need no resident agent process, only SSH (Windows uses WinRM/PSRP/SSH) and Python; Push model: the control node actively connects to managed nodes to run tasks, rather than managed nodes periodically pulling configuration from a server.
In-depth answer
- Benefits: quick to get started, no agent upgrade, certificate or port management burden, and well suited to ad-hoc orchestration (rolling releases, incident response).
- Trade-offs: the control node must be able to reach every host; at scale it relies on concurrency and connection tuning; without an agent there is no “continuous self-healing”, so you need scheduled runs (AWX scheduled jobs) or
ansible-pullto implement pull mode. - Code still runs “temporarily” on managed nodes: modules are packaged, sent over, executed, and then deleted.
Common follow-up questions
- Does agentless mean there are no dependencies at all? It needs SSH and a supported Python version (2.21 requires 3.9–3.14 on managed nodes); network devices use connection methods such as network_cli that do not need Python.
- Can you use pull mode?
ansible-pull: the node pulls from Git and runs locally.
Bonus points
Point out that push mode suits “ordered orchestration” well (drain traffic, upgrade, then re-add), which is a weakness of pure pull-mode tools.
Common wrong answers
“Ansible never executes anything on the target machine”; “Ansible is declarative, so it is the same as Terraform” (it executes tasks in order; the modules themselves are mostly declarative and idempotent).
See Lesson 1 Module 1.
Q2. Describe what Ansible does on the control node and on the managed node when executing one playbook task.Intermediate
30-second answer
The control node parses the inventory and playbook, merges variables per host, renders task arguments with Jinja2, and once it finds the module, uses AnsiballZ to package the module code and its dependencies into a self-extracting Python file; through the connection plugin (SSH) it creates a temp directory on the remote host, uploads the file (or streams it via stdin when pipelining is enabled), applies become if needed, and runs it with the remote Python; the module returns JSON, the control node uses it to decide ok/changed/failed, and the callback plugin then produces the output.
In-depth answer
ANSIBLE_KEEP_REMOTE_FILES=1 ansible node1 -m ping -vvv 2>&1 | grep -E 'EXEC|PUT' # EXEC ... mkdir -p ~/.ansible/tmp/ansible-tmp-... create temp directory # PUT .../tmpXXXX TO .../AnsiballZ_ping.py transfer module # EXEC ... python3 .../AnsiballZ_ping.py run (wrapped in sudo when become is used)
- action plugin runs first on the control node (for example, template renders the file on the control node and then calls the copy module to transfer it), which is why templates are always rendered on the control node.
- With the linear strategy, all hosts finish the current task before any host moves on to the next; forks sets the concurrency.
Common follow-up questions
- What does pipelining change? It skips temp files and extra round trips, but conflicts with sudo requiretty (Part A, Issue 7).
- Why does the raw module not need Python? It runs the command directly over SSH, without going through AnsiballZ.
Bonus points
Mention AnsiballZ_*.py explode/execute debugging method (#37), and which phases correspond to UNREACHABLE and FAILED (#1–#11).
Common wrong answers
“The module runs on the control node and then pushes the result over” (only action plugins and tasks with delegate_to: localhost run locally).
Q3. What is the difference between ansible-core, the Ansible community package, AWX, and Red Hat AAP?Beginner
30-second answer
ansible-core is the engine (command line, language, ansible.builtin modules); Ansible community package (e.g., 14.x, based on core 2.21) = ansible-core + a curated set of collections; AWX is the open-source web/API control platform (upstream project); Red Hat Ansible Automation Platform (AAP, currently 2.6) is a commercial product that includes the automation controller, automation hub (private Automation Hub), EDA controller, execution environments and support.
In-depth answer
| Component | Purpose | Release cadence |
|---|---|---|
| ansible-core | Engine | A major release about every six months; three versions maintained (currently 2.21/2.20/2.19) |
| ansible (community package) | core + collections | Major version matching core |
| AWX | Open-source controller, deployed on Kubernetes with the AWX Operator | Frequent releases, no long-term support |
| AAP | Enterprise platform: controller + Hub + EDA + certified content | 2.6 is the last version supporting RPM installation (RHEL 9); from 2.7 onward, container-based installation only |
Common follow-up questions
- Is installing only ansible-core enough? Yes, but you need to install the required collections with requirements.yml; in production, a version-pinned EE is recommended.
- Can AWX be used in production? Yes, but there is no vendor support or long-term maintained release, so you must validate upgrades yourself.
Bonus points
Be able to explain why the version support policy matters: when upgrading core, check managed-node Python requirements and the porting guide (#9, #18).
Common wrong answers
“AWX is the free version of AAP with exactly the same features” (AAP includes certified content, Hub, support and lifecycle commitments, among others).
See Lesson 5 Module 4.
Q4. What is idempotence? How does Ansible ensure it? What breaks it?Beginner
30-second answer
Idempotence means repeating a run gives the same result, with no change the second time. Most Ansible modules are declarative: they check the current state, compare it with the desired state, and only change and report changed when the two differ. command/shell don't understand their semantics, so they always report changed and need creates/removes/changed_when to be idempotent.
In-depth answer
- ansible.builtin.user: { name: deploy, state: present } # idempotent by design
- ansible.builtin.command: /opt/app/bin/migrate
register: m
changed_when: "'No migrations to apply' not in m.stdout" # define “changed” manually
Common causes that break idempotence: shell/command, appending to files,lineinfile , regex mismatches (#36), templates with timestamps,get_url pointing to a “latest” link.
Common follow-up questions
- How do you verify? Run it twice in a row and check for changed=0; Molecule's idempotence step automates this check.
- Does idempotence mean safe to re-run? Broadly yes, but you also need to handle partial state left by mid-run failures (use block/rescue).
Bonus points
Point out that idempotence is the prerequisite for check mode and drift detection (Question 47).
Common wrong answers
“All Ansible modules are idempotent”; “idempotent means it never errors”.
See Lesson 1 Module 4.
Q5. Explain inventory: static and dynamic inventories, groups, group_vars/host_vars.Beginner
30-second answer
An inventory defines “which hosts to manage, how they are grouped, and each host's connection parameters and variables”. A static inventory is an INI or YAML file; a dynamic inventory is generated live by plugins (aws_ec2, azure_rm, etc.) from sources such as cloud APIs. Groups can be nested (children), and the implicit groups are all and ungrouped are implicit groups; group_vars/ and host_vars/ directories at the same level as the inventory or playbook are loaded automatically.
In-depth answer
# inventories/prod/hosts.yml
all:
children:
web:
hosts:
web1: { ansible_host: 10.0.1.11 }
web2: { ansible_host: 10.0.1.12 }
db:
hosts:
db1: { ansible_host: 10.0.2.21 }
prod:
children: { web: {}, db: {} }
ansible-inventory -i inventories/prod --graph ansible-inventory -i inventories/prod --host web1
Common follow-up questions
- Multiple inventory sources? Yes, point
-iat a directory; multiple sources in it are merged (static + dynamic). - How do you group dynamic inventories?
keyed_groups(by tag),groups(Jinja2 conditions),compose(generated variables, such as ansible_host).
Bonus points
Split inventory directories by environment to keep staging variables from leaking into prod; assert in CI that key groups are non-empty (#44).
Common wrong answers
Putting group_vars in an arbitrary directory and expecting it to load (#13); using inventory file names to separate environments while sharing one group_vars.
Q6. When are ad-hoc commands and playbooks each appropriate?Beginner
30-second answer
Ad-hoc (ansible pattern -m module -a args) suit one-off queries and emergency operations, such as checking disks in bulk or restarting services; playbooks suit work that needs reuse, review, version control and multi-step orchestration.
In-depth answer
ansible web -m ansible.builtin.shell -a 'df -h / | tail -1' -o ansible web -b -m ansible.builtin.service -a 'name=nginx state=restarted' --limit web1 ansible all -m ansible.builtin.setup -a 'filter=ansible_distribution*'
In production, ad-hoc changes should be controlled: use AWX's ad-hoc command feature to leave an audit trail, or turn frequent operations into playbooks.
Common follow-up questions
- Can ad-hoc use become and check? Yes:
-b,-C,-D.
Bonus points
Mention that ad-hoc is a powerful troubleshooting tool (many diagnostic commands in Part A are ad-hoc), but changes should go through code review.
Common wrong answers
“All production changes can be made quickly with ad-hoc” (no audit trail, not reproducible).
See Lesson 1 Module 3.
Q7. Which connection plugins does Ansible have? How do you manage Windows, containers and cloud hosts without SSH?Intermediate
30-second answer
Connection plugins decide “how to reach a host and run commands”: ssh (default, OpenSSH),paramiko_ssh,local; Windows uses winrm,psrp or SSH; containers/clusters use community.docker.docker,kubernetes.core.kubectl; for AWS without SSH, use amazon.aws.aws_ssm; network devices use network_cli,httpapi,netconf.
In-depth answer
# group_vars/aws_private.yml — manage private-subnet EC2 via SSM, no need to open port 22 ansible_connection: amazon.aws.aws_ssm ansible_aws_ssm_region: ca-central-1 ansible_aws_ssm_bucket_name: my-ssm-transfer-bucket # file transfer requires an S3 bucket
The SSM plugin requires session-manager-plugin on the control node, and the instance must run the SSM Agent and have the appropriate IAM permissions.
Common follow-up questions
- What is the difference between WinRM and PSRP? PSRP uses the PowerShell Remoting protocol and is usually faster and more capable; both depend on Python libraries on the control node (pywinrm / pypsrp).
- Is it appropriate to manage the inside of containers with Ansible? Generally not recommended, since containers should be immutable; it is better to use Ansible to build images or orchestrate deployments.
Bonus points
Connect connection plugins to the security model: SSM/Bastion reduces exposure and sessions are auditable (Lesson 4).
Common wrong answers
“Ansible can only manage Linux over SSH”.
Q8. What is the difference between a module and a plugin?Intermediate
30-second answer
Modules are programs sent to managed nodes (or localhost) to run, complete one unit of work and return JSON; Plugins run on the control node, extending the Ansible engine itself: connection, inventory, lookup, filter, test, callback, become, cache, strategy, vars, etc.
In-depth answer
| Module | Plugin | |
|---|---|---|
| Where it runs | Managed node (most) | Control node |
| Examples | apt, user, template (action plugin + copy module) | ssh, aws_ec2 inventory, to_nice_yaml filter, profile_tasks callback |
| Where dependencies live | Managed node's Python (#28) | Control node / EE (#27, #46) |
Common follow-up questions
- Is template a module or a plugin? Both: the action plugin renders on the control node, then calls a module to write the file.
Bonus points
Use the practical question “where should dependencies be installed?” to explain the difference.
Common wrong answers
“Plugins are just third-party modules.”
See Lesson 7 Module 7.
Q9. What are facts? How do you customize, cache and speed up fact gathering?Intermediate
30-second answer
Facts are the host information collected by the setup module (OS, network, hardware, etc.), stored in ansible_facts. You can use /etc/ansible/facts.d/*.fact to provide custom (local) facts; use fact caching (jsonfile, redis, etc.) + gathering = smart to avoid repeated gathering; use gather_subset to gather only the parts you need.
In-depth answer
- hosts: web
gather_subset: ['!hardware', network]
tasks:
- ansible.builtin.debug: { msg: "{{ ansible_facts.default_ipv4.address }}" }
- ansible.builtin.debug: { msg: "{{ ansible_local.app.version | default('n/a') }}" } # facts.d/app.fact
Common follow-up questions
- Why can't I reference other hosts' facts with --limit? They are not part of the play; use fact caching or delegate_facts (#20).
- INJECT_FACTS_AS_VARS? Legacy top-level variables
ansible_hostname; preferansible_facts['hostname'], whose injection behavior may change in the future, so follow the official docs.
Bonus points
Mention that the hardware subset hangs on a stale NFS mount (#40).
Common wrong answers
“Facts must always be gathered.”
Q10. What is the difference between Ansible and Terraform? When do you combine them?Intermediate
30-second answer
Terraform is a declarative infrastructure provisioning tool that maintains state, computes the dependency graph, generates plans, and excels at creating, modifying and destroying cloud resources; Ansible excels at OS and application-layer configuration and orchestration, executing tasks in order with no central state. A common combination: Terraform creates networks, VMs and databases, and Ansible configures those hosts via dynamic inventory and deploys the application.
In-depth answer
| Terraform | Ansible | |
|---|---|---|
| Model | Declarative + state + plan | Task sequence; modules are mostly declarative |
| Removing resources | Removing from code destroys them | Requires explicit state: absent |
| Drift detection | plan | --check --diff (relies on idempotence) |
| Strengths | Cloud resource lifecycle | OS configuration, app release, ordered orchestration, ad-hoc operations |
Common follow-up questions
- Can Ansible create cloud resources? Yes (azure.azcollection, amazon.aws); suitable for simple or one-off scenarios, but no plan/state lifecycle management.
- How do they connect? Use cloud tags + dynamic inventory, or generate an inventory from Terraform outputs (Question 49).
Bonus points
Point out the “immutable infrastructure” approach: Packer + Ansible build images, Terraform deploys them, and configuration is no longer changed at runtime.
Common wrong answers
“The two can completely replace each other.”
See Lesson 3 Module 6.
Q11. What do execution strategy (strategy), forks and serial each control?Intermediate
30-second answer
forks controls how many hosts are connected at the same time; strategy controls how tasks advance: linear (default: all hosts finish a task before the next one),free (each host runs as fast as it can),host_pinned,debug; serial runs the whole play in batches across hosts (rolling update).
In-depth answer
- hosts: web serial: [1, "25%", "50%"] # 1 canary host first, then 25%, then 50% max_fail_percentage: 10 strategy: linear tasks: [...]
Common follow-up questions
- How do serial and forks relate? serial sets the batch of hosts, forks sets concurrency within a batch; with serial=10 and forks=5, a batch still runs in two rounds.
- throttle? A per-task concurrency cap, used to limit load on shared resources (such as an API).
Bonus points
Point out the risk of the free strategy: it cannot be used when hosts depend on each other (for example, DB before app).
Common wrong answers
“serial is just an alias for forks.”
Q12. How does become work? What are the risks and pitfalls when become_user is not root?Intermediate
30-second answer
On the remote host, become switches identity to run modules via sudo (default), su, doas, runas, and so on. Ansible uses a random prompt string to recognize the password prompt and fills in the become password. When switching to an unprivileged user, the user must be able to read the temp module file uploaded by the SSH user, which relies on setfacl or similar (it fails without the acl package), or uses pipelining to bypass it.
In-depth answer
- name: Create DB user as postgres
community.postgresql.postgresql_user: { name: app }
become: true
become_user: postgres
become_method: ansible.builtin.sudo
Common errors are listed in Part A: #5 Missing sudo password, #6 Incorrect/Timeout, #7 requiretty, #10 unprivileged user.
Common follow-up questions
- How do you minimize privileges? Use a dedicated deployment account, restrict commands in sudoers, use key authentication, and audit sudo logs; avoid become for any task that does not need it.
- Where do you store the become password? In Vault or an AWX Machine credential.
Bonus points
Mention allow_world_readable_tmpfiles is insecure, and that since 2.19 become timeouts are classified as unreachable.
Common wrong answers
“Setting become: true on the whole play is the easiest” (violates least privilege, and file ownership ends up as root).
See Lesson 7 Module 3.
Q13. What is the lookup order for ansible.cfg? How do you confirm which configuration is in effect?Beginner
30-second answer
Use the first one found, in this order: the file specified by environment variable ANSIBLE_CONFIG → the current directory's ansible.cfg → ~/.ansible.cfg → /etc/ansible/ansible.cfg. Only one file is used, not merged. Individual settings can also be overridden by ANSIBLE_* environment variables and command-line arguments.
In-depth answer
ansible --version | grep 'config file' ansible-config dump --only-changed # show non-default values and their sources ansible-config init --disabled -t all > ansible.cfg.example
Common follow-up questions
- Why doesn't ansible.cfg take effect in CI? It is ignored when the current directory is world-writable (#49).
Bonus points
Commit the project-level ansible.cfg with the code, and avoid depending on a personal ~/.ansible.cfg.
Common wrong answers
“Multiple ansible.cfg files are merged.”
See Lesson 1 Module 1.
Scenario 5-1: Moving from manual SSH operations to Ansible
A team maintains 300 Linux servers, mostly by logging in over SSH and running shell scripts; configuration drifts badly between machines. You are asked to introduce Ansible within one quarter. What is your rollout plan? How do you prove the value?
Key points of the reference answer
- Phase 1 (read-only): build the inventory (static first, then dynamic), use ad-hoc to collect facts and configuration differences, and produce a “drift report” — zero risk, and it earns trust.
- Phase 2 (baseline): write baseline roles (users, SSH, time sync, logging, monitoring agents), test first on a test group with
--check --diff, then apply in batches (serial). - Phase 3 (process): Git + code review + ansible-lint + Molecule; AWX provides RBAC, credential management, scheduling and auditing.
- Metrics: lead time for changes, failure rate, number of drift items, and time to bring a new machine online.
- Risks: inconsistent Python versions (#9), inconsistent sudo baselines (#5–#7), and team skills; address them with training and pair work.
Scenario 5-2: Choosing push or pull
The company has 8,000 edge devices across multiple data centers, with unstable networks, and some devices have only outbound access. How would you design this with Ansible?
Key points of the reference answer
- Push depends on inbound connectivity and network quality; deploy AWX execution nodes in each data center (automation mesh / instance groups) and push locally.
- Devices with only outbound access:
ansible-pullperiodically pulls from Git and runs locally, reporting results via callbacks; or use EDA / a message queue to trigger it. - Combined approach: use pull for baseline configuration to guarantee eventual consistency, and push for urgent orchestration.
- Watch signing and the supply chain: repositories and collections that devices pull must be verified (Question 48).
Teaching videos (titles and channels verified via YouTube oEmbed)
No verified video on Ansible interview questions was found. Use this module's “mock interview” to record yourself and play it back.
Official docs
Module 6 · Part B: Playbooks, variables and roles (Questions 14–25)
- Explain a practical version of variable precedence, and the difference between defaults and vars.
- Explain the semantics and pitfalls of import/include, handlers, block/rescue, tags, and delegate_to/run_once/serial.
- Design a reusable, testable role and collection structure.
Skim the questions and focus areas first; click a row to jump to the details.
Q14. Explain Ansible variable precedence. What is the difference between role defaults and role vars?Intermediate
30-second answer
The official docs list over twenty precedence levels; a practical memory aid: role defaults (lowest) → inventory variables (group_vars/all → specific group → host_vars) → facts → play vars / vars_files → role vars → block/task vars → set_fact/register → extra vars (-e) (highest). Defaults are “default values users can override”, vars are “role-internal constants”, and vars rank above inventory variables.
In-depth answer
Same-level groups are merged alphabetically, child groups override parent groups, and you can adjust this with ansible_group_priority ; dictionaries are replaced as a whole by default, so use combine. Troubleshooting: check at the inventory level with ansible-inventory --host ,debug to see final values, and grep to find all definition locations.
nginx_conf: "{{ nginx_conf_defaults | combine(nginx_conf_overrides | default({}), recursive=True) }}"
Common follow-up questions
- Does the set_fact value still exist in the next play? Yes, it persists as a fact for that host (and has very high precedence).
- How do you avoid confusion? Define variables only in defaults, inventory group_vars and Vault, and prefix variables with the role name.
Bonus points
Cite a real case: putting tunable parameters in vars/ made inventory overrides ineffective (Part A, Issue 14).
Common wrong answers
“host_vars always has the highest precedence”; “defaults and vars are the same”.
See Lesson 2 Module 3.
Q15. What is the execution order of a play? How are pre_tasks, roles, tasks, post_tasks and handlers ordered?Beginner
30-second answer
Gather facts → pre_tasks → flush handlers → roles → tasks → flush handlers → post_tasks → flush handlers. Handlers run at the end of each stage (or when meta: flush_handlers).
In-depth answer
- hosts: web
serial: 1
pre_tasks:
- name: Drain from LB
community.general.haproxy: { state: disabled, host: "{{ inventory_hostname }}" }
delegate_to: "{{ item }}"
loop: "{{ groups['lb'] }}"
roles: [myapp]
post_tasks:
- ansible.builtin.uri: { url: "http://{{ ansible_host }}:8000/healthz" }
- name: Enable in LB
community.general.haproxy: { state: enabled, host: "{{ inventory_hostname }}" }
delegate_to: "{{ item }}"
loop: "{{ groups['lb'] }}"
Common follow-up questions
- How do roles and include_role differ when placed in tasks? The roles keyword statically imports and runs before tasks; include_role is dynamic and runs where it appears.
Bonus points
Use a rolling-release example to explain the value of pre_tasks and post_tasks (Lesson 6).
Common wrong answers
“Handlers run immediately after being notified.”
Q16. What is the semantics of handlers? What are listen and flush_handlers for?Beginner
30-second answer
A handler is a task that runs only when notified (and the task that notifies it reports changed). The same handler runs only once per flush, and handlers run in the order they are defined in the handlers section, not in notification order. Use listen to let several handlers subscribe to the same topic; use meta: flush_handlers to run already-notified handlers immediately.
In-depth answer
Pitfalls: name mismatches, notifications lost when a run fails midway (--force-handlers), needing a change to take effect before a health check but never flushing (Part A, Issue 31). For config files, use validate to avoid restarting onto a bad configuration.
Common follow-up questions
- Can a handler notify another handler? Yes, a handler can also notify.
- Handler scope in roles? Role handlers are visible to the whole play; you can reference them precisely in the form
role name : handler name(see the docs for details).
Bonus points
Explain the trade-off between “restart vs reload”, and that in serial scenarios handlers run for each batch.
Common wrong answers
“A handler runs once every time it is notified.”
See Lesson 1 Module 6.
Q17. What is the difference between import_* and include_*? When is each appropriate?Intermediate
30-second answer
import is static: expanded at parse time, tags/when copied to each child task, and the tasks appear in --list-tasks , cannot be used in loops, and file names cannot depend on runtime variables. include is dynamic: loaded when execution reaches it; it can be looped and file names can be chosen with facts, but tags/when only apply to the include statement itself (you need apply to pass them down).
In-depth answer
- ansible.builtin.import_tasks: hardening.yml # static, can be selected by tag
tags: hardening
- ansible.builtin.include_tasks: "{{ ansible_facts.os_family | lower }}.yml" # dynamic
- ansible.builtin.include_role:
name: user
loop: "{{ users }}"
loop_control: { loop_var: user_item }
Common follow-up questions
- What pitfalls come with when on import? Each child task is evaluated separately; a later task may be skipped after an earlier task changes state (Part A, Issue 23).
- Is include: still usable? Removed in ansible-core 2.16 (#30).
Bonus points
Team convention: “import by default; include only when dynamic behavior is needed.”
Common wrong answers
“The two are just different names.”
See Lesson 2 Module 1.
Q18. What is the directory structure of a role? How do you design a good role?Intermediate
30-second answer
Standard structure: tasks/ handlers/ defaults/ vars/ templates/ files/ meta/ (including meta/main.yml dependencies and meta/argument_specs.yml argument validation) and molecule/ tests. A good role has a single responsibility, documents all parameters in defaults, validates input, is idempotent, runs in check mode, and has Molecule tests.
In-depth answer
# roles/myapp/meta/argument_specs.yml
argument_specs:
main:
options:
myapp_port: { type: int, default: 8000, description: "listen port" }
myapp_version: { type: str, required: true }
Common follow-up questions
- Dependencies between roles?
meta/main.ymldependencies (run automatically first); this easily creates hidden coupling, so listing them explicitly in the playbook is preferred. - Role or collection? Package multiple roles, plugins and modules into a collection when you need to distribute them.
Bonus points
Mention that argument_specs can catch type errors when a run starts (Part A, Issues 16 and 17).
Common wrong answers
“One site role contains everything.”
See Lesson 2 Module 1.
Q19. Where does Jinja2 evaluate in Ansible? What are the differences between filter, test and lookup?Intermediate
30-second answer
All templates are evaluated on the control node, per host. filter transform data (| default,| to_nice_yaml,| combine); test return booleans (is defined,is version,is succeeded); lookup fetches data from external sources (files, environment variables, password stores), also on the control node.
In-depth answer
{{ users | selectattr('active') | map(attribute='name') | join(',') }}
{% if ansible_facts.distribution_version is version('24.04', '>=') %}...{% endif %}
{{ lookup('ansible.builtin.env', 'HOME') }} {{ query('ansible.builtin.fileglob', 'files/*.conf') }}
Changes since 2.19: conditions must be booleans, and conditions cannot contain nested {{ }}, only render trusted templates (Part A, Issues 18 and 19).
Common follow-up questions
- Which machine's file does lookup read? The control node. To read remote files, use slurp/fetch.
- What is the difference between lookup and query? query always returns a list (#22).
Bonus points
Mention !unsafe and {% raw %} handle conflicts with other template syntax (#21).
Common wrong answers
“Templates are rendered on the target machine.”
See Lesson 1 Module 7.
Q20. What is the difference between loop and with_*? How do until/retries work?Beginner
30-second answer
loop is the recommended syntax and only accepts lists; with_* is the older lookup-based syntax (still works), auto-flattens nested lists, etc. Use loop_control to set label,loop_var,pause,index_var. until + retries + delay are used for “retry until the condition is met”.
In-depth answer
- ansible.builtin.uri: { url: "http://localhost:8000/healthz", status_code: 200 }
register: hc
until: hc is succeeded
retries: 30
delay: 2
- ansible.builtin.user: { name: "{{ item.name }}", groups: "{{ item.groups }}" }
loop: "{{ users }}"
loop_control: { label: "{{ item.name }}" }
Common follow-up questions
- Should I use loop for 30 packages? No; pass the list directly to apt's name parameter to run in one go (#39).
Bonus points
For nested loops, use subelements/product filter; when looping with include_role, change loop_var to avoid conflicts.
Common wrong answers
“loop and with_items are exactly the same” (flattening behavior differs).
See Lesson 1 Module 6.
Q21. How does Ansible handle errors? What are the differences between block/rescue/always, failed_when and ignore_errors?Intermediate
30-second answer
block/rescue/always similar to try/catch/finally; failed_when/changed_when custom failure conditions; ignore_errors continue past failures (use with caution); ignore_unreachable ignore unreachable hosts; play-level any_errors_fatal,max_fail_percentage control the global failure policy.
In-depth answer
- block:
- ansible.builtin.include_tasks: deploy.yml
rescue:
- ansible.builtin.include_tasks: rollback.yml
- ansible.builtin.fail: { msg: "Deploy failed on {{ inventory_hostname }}, rolled back" }
always:
- ansible.builtin.include_tasks: enable_in_lb.yml
Common follow-up questions
- Does the host count as failed after rescue? When the rescue succeeds, the task counts as rescued and the host continues; to make it still fail, add a fail at the end of rescue.
- ansible_failed_task / ansible_failed_result? Magic variables available in rescue.
Bonus points
Explain that ignore_errors hides problems, so pair it with register and subsequent checks.
Common wrong answers
“ignore_errors can ignore UNREACHABLE” (requires ignore_unreachable).
See Lesson 2 Module 5.
Q22. What are the common magic variables? How are hostvars, groups and inventory_hostname used?Beginner
30-second answer
inventory_hostname (name in the inventory),ansible_host (connection address),groups (group-to-host list mapping),group_names (groups the current host belongs to),hostvars (variables and facts for all hosts),ansible_play_hosts,ansible_check_mode,role_path,ansible_playbook_python etc.
In-depth answer
upstream app {
{% for h in groups['app'] %}
server {{ hostvars[h].ansible_host }}:8000;
{% endfor %}
}
Common follow-up questions
- hostvars lookup of another host's facts reports not found? It was not part of the play (Part A, Issue 20).
- What is the difference between register and set_fact? register stores task results; set_fact defines custom variables; both are stored per host.
Bonus points
Distinguish inventory_hostname from ansible_hostname (the latter is a fact, taken from the remote hostname).
Common wrong answers
“inventory_hostname is the IP address.”
See Lesson 1 Module 5.
Q23. How do tags and --limit work? What is special about the always and never tags?Beginner
30-second answer
--tags/--skip-tags select tasks; --limit select hosts. always tagged tasks run unless explicitly skipped; never tagged tasks do not run unless explicitly requested (suited to dangerous operations, such as database resets).
In-depth answer
ansible-playbook site.yml --tags config --limit 'web:&canadacentral' --check --diff ansible-playbook site.yml --list-tags ansible-playbook db.yml --tags reset_db # runs the never task only when explicitly requested
Common follow-up questions
- Tasks inside include are not selected by tag? Use apply or import (Part A, Issue 23).
Bonus points
Standardize tags by function rather than by task, and assert with list-tasks in CI.
Common wrong answers
“--limit can select tasks.”
See Lesson 2 Module 6.
Q24. What is a collection? What does FQCN mean? How do you manage dependencies?Intermediate
30-second answer
A collection is the distribution unit for Ansible content, containing modules, plugins, roles, playbooks and docs, named namespace.name. FQCN (for example, community.docker.docker_container) removes ambiguity between same-named modules so resolution is deterministic. Dependencies are listed in collections/requirements.yml and pinned, installed via ansible-galaxy or built into the EE.
In-depth answer
collections:
- name: amazon.aws
version: ">=10.0.0,<12.0.0"
- name: https://git.example.com/infra/acme.infra.git
type: git
version: v1.4.2
Common follow-up questions
- When multiple versions of the same collection exist, which one is used? The first one found in COLLECTIONS_PATHS (Part A, Issue 38).
- How are private collections distributed? Private Automation Hub, Galaxy NG, a Git repository or a tarball.
Bonus points
Mention collection signing and ansible-galaxy collection verify (Question 48).
Common wrong answers
“Short names are cleaner, so there is no need to write FQCN.”
See Lesson 2 Module 2.
Q25. What problems do delegate_to, run_once, local_action and serial each solve?Advanced
30-second answer
delegate_to running a task on another host while still using the current host's variable context (e.g. removing the current web node from the LB); run_once running once across the whole batch (e.g. a database migration); local_action/delegate_to: localhost running on the control node (calling an API); serial running the whole play in rolling batches.
Deeper answer
- hosts: web
serial: "25%"
max_fail_percentage: 0
tasks:
- name: DB migration once per run
ansible.builtin.command: /opt/app/bin/migrate
run_once: true
delegate_to: "{{ groups['app'][0] }}"
- name: Remove from LB
community.general.haproxy: { state: disabled, host: "{{ inventory_hostname }}" }
delegate_to: "{{ item }}"
loop: "{{ groups['lb'] }}"
Common interviewer follow-ups
- How many times does run_once run under serial? Once per batch. Put the migration in a separate play, or use a condition to guarantee it runs only once.
- With delegate_to, which host's connection variables are used? The connection parameters of the delegated host, but template variables still come from the current host; facts are written back to the current host by default (
delegate_factscan be changed).
Bonus points
Combine them into a zero-downtime release flow (Question 45, Lesson 6).
Common wrong answer
“delegate_to switches the task along with its variables over to another host.”
Scenario 6-1: Design a multi-environment repository structure
The company has dev / staging / prod environments, one set on Azure and one on AWS, and 20 applications share a common set of base roles. Design the Ansible repository structure, variable organization, and secrets management.
Key points of the reference answer
- Structure:
inventories/{dev,staging,prod}/(each with its own hosts or dynamic inventory + group_vars/host_vars)playbooks/; extract base roles into an internal collectionacme.platform, versioned independently; application roles live in the application repo or a collection. - Variables: role defaults provide the defaults; environment differences are written only in the matching inventory's group_vars; cloud differences use
azure/awsper-cloud groups. - Secrets: a separate vault-id per environment, or look up at runtime from Key Vault / Secrets Manager; prod passwords live only in AWX credentials.
- Quality: lint + Molecule + for each environment
ansible-inventory --graphassertions; unify EE dependencies.
Scenario 6-2: Run a database migration only once
10 application servers use serial: 2 rolling updates, and a database schema migration must run once during the release. How do you guarantee the migration runs exactly once and completes before the new code goes live?
Key points of the reference answer
- Put the migration in a separate play that runs before the release play:
hosts: app[0]orrun_once: trueand that play does not set serial. - Migrations must be backward compatible (expand-contract pattern) so old code keeps working during the rolling update.
- The migration tool is itself idempotent (it records a version table), and a failure stops the whole release (
any_errors_fatal). - Explain why run_once cannot be used directly in a serial play: it would run once per batch.
Scenario 6-3: A role's parameters keep growing
An nginx role already has 80 variables, and users often pass the wrong type or misspell a variable name without any error. How do you govern it?
Key points of the reference answer
- Introduce
meta/argument_specs.yml: type, required, choices, and defaults, validated at the start of the run. - Consolidate scattered variables into a few structured dictionaries +
combine, or have callers supply template fragments directly. - Misspelled variable names: ansible-lint's var-naming rule + a role prefix; document the defaults.
- Molecule scenarios cover common combinations; use semantic versioning, with breaking changes in a major version.
Teaching videos (titles and channels verified via YouTube oEmbed)
No verified video specifically on Ansible interview questions was found.
Official docs
Module 7 · Part B: Modules, Plugins and Testing (Questions 26–38)
- Write a custom module skeleton that supports check mode, plus a filter plugin.
- Explain which test layer each of lint / syntax-check / Molecule / ansible-test covers.
- Master systematic methods for debugging and performance tuning, and be ready to answer follow-ups on async, callback plugins, and so on.
Skim the questions and what they test first; click a row to jump to the details.
Q26. How are modules executed on managed nodes? What is AnsiballZ?Advanced
30-second answer
The control node packages the module code,module_utils dependencies, and arguments into a self-contained Python script (AnsiballZ, which is a base64-encoded zip internally) and sends it to the remote host to run. The script unpacks to a temp location and runs the module; the module reads its input from the arguments, prints a single JSON object to stdout, and then the temp files are cleaned up.
Deeper answer
With pipelining enabled, the script is fed to the remote Python via stdin and never written to disk. Non-Python modules (such as PowerShell modules) are handled by their own wrappers; “old-style” and binary modules are also supported, but modern collections are almost all AnsiballZ. Debugging: ANSIBLE_KEEP_REMOTE_FILES=1 then python3 AnsiballZ_x.py explode you get debug_dir, after editing, run execute (Part A #37).
Common interviewer follow-ups
- Why must module output be pure JSON? The control node has to parse the return value; anything printed by a remote login script breaks parsing.
- What is module_utils? Shared library code across modules, embedded at packaging time as needed.
Bonus points
Be able to map each step to the errors it can produce (Figure 1-1).
Common wrong answer
“Ansible installs the module package on the target machine.”
Q27. How do you write a custom module? How do you support check mode and diff?Advanced
30-second answer
Write it in Python, using AnsibleModule: declare argument_spec (type, required, default, choices, no_log) and supports_check_mode=True; read the current state → compute the required changes → in check mode, only report without executing → use exit_json(changed=..., diff=...) or fail_json(msg=...) to return results. Place it in the role/project's library/ or the collection's plugins/modules/.
Deeper answer
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type="path", required=True),
value=dict(type="str", required=True),
),
supports_check_mode=True,
)
p, v = module.params["path"], module.params["value"]
try:
current = open(p).read().strip()
except FileNotFoundError:
current = None
changed = current != v
result = dict(changed=changed, diff=dict(before=current or "", after=v))
if changed and not module.check_mode:
with open(p, "w") as f:
f.write(v + "\n")
module.exit_json(**result)
if __name__ == "__main__":
main()
You also need DOCUMENTATION/EXAMPLES/RETURN a docstring (ansible-doc and ansible-test sanity check it).
Common interviewer follow-ups
- When should you write a module instead of using shell? When you need idempotency, check mode, structured return values, or reuse.
- How do you test it? ansible-test units / sanity / integration (Q32).
Bonus points
Sensitive parameters no_log=True; use module.run_command rather than subprocess; write files atomically (module.atomic_move).
Common wrong answer
“Just print the result from the module.”
See Lesson 7 Module 7.
Q28. What plugin types does Ansible have? Give one use case for each.Intermediate
30-second answer
connection (ssh, winrm, aws_ssm), inventory (aws_ec2, azure_rm), lookup (file, env, hashi_vault), filter (combine, custom transforms), test (version, custom checks), callback (profile_tasks, json, logging/notifications), become (sudo, su), cache (jsonfile, redis fact cache), strategy (linear, free), vars (host_group_vars loads group_vars), module_utils and doc_fragments (for development), etc.
Deeper answer
Plugins all run on the control node; put them in a collection's plugins/<type>/ or the project's filter_plugins/,callback_plugins/ and similar directories. ansible-doc -t callback -l You can list plugins of one type.
Common interviewer follow-ups
- Who loads group_vars? vars plugin
host_group_vars.
Bonus points
Be able to name custom plugins you have written or used (for example, a CMDB used as an inventory plugin).
Common wrong answer
Only knowing filter and lookup.
Q29. Write a custom filter plugin, and explain when to write a filter instead of complex Jinja2.Intermediate
30-second answer
A filter is a Python class FilterModule, which returns filters() a name-to-function mapping. Write a filter when a Jinja2 expression runs past one line, is hard to read, or needs unit tests.
Deeper answer
# filter_plugins/net.py (or the collection's plugins/filter/)
def to_upstreams(hosts, hostvars, port=8000):
return [f"{hostvars[h]['ansible_host']}:{port}" for h in hosts]
class FilterModule:
def filters(self):
return {"to_upstreams": to_upstreams}
{% for s in groups['app'] | to_upstreams(hostvars, 8000) %}server {{ s }};
{% endfor %}
Common interviewer follow-ups
- Where does a filter run? On the control node, at render time.
- How do you test it? Plain pytest, or the collection's ansible-test units.
Bonus points
Since 2.19, return value types and undefined handling are stricter, so filters should explicitly handle missing keys.
Common wrong answer
“Filters run on managed nodes.”
See Lesson 7 Module 7.
Q30. What is the difference between the command, shell, raw, and script modules?Beginner
30-second answer
command runs a program directly without a shell (no pipes, redirection, or variable expansion), which is safer; shell runs through /bin/sh, which supports pipes and so on; raw runs directly over SSH and does not need Python (used for bootstrapping); script copies a local script to the remote host and runs it.
Deeper answer
- ansible.builtin.command: { argv: [/opt/app/bin/ctl, reload, "{{ name }}"] } # pass arguments safely
- ansible.builtin.shell: set -o pipefail && journalctl -u app | tail -50
args: { executable: /bin/bash }
changed_when: false
Common interviewer follow-ups
- What are the risks of shell? Variable injection (use
| quote) to escape it; pipe failures are ignored (pipefail); not idempotent (#26).
Bonus points
The ansible-lint command-instead-of-shell,risky-shell-pipe rules.
Common wrong answer
“shell and command are the same thing, just with different names.”
See Lesson 1 Module 3.
Q31. What are check mode and diff mode? What are their limitations?Intermediate
30-second answer
--check (dry run) makes modules that support check only report what would change, without executing; --diff shows before/after differences for files and similar content. Limitations: modules without check support are skipped; tasks that depend on the real result of an earlier step are predicted inaccurately; command/shell are skipped by default (Part A #32).
Deeper answer
Task-level control: check_mode: false (always run, good for read-only probes),check_mode: true (always dry run); diff: false hide sensitive file diffs; the variable ansible_check_mode is used in conditionals.
Common interviewer follow-ups
- Does diff leak secrets? Yes. When rendering a template with passwords, set
diff: falseand pair it with no_log.
Bonus points
Use check+diff as change review (dry-run prod in CI and attach the output to the PR) and as a drift detection method (Question 47).
Common wrong answer
“Check mode is 100% accurate.”
See Lesson 2 Module 6.
Q32. How do you test Ansible code? What do lint, syntax-check, Molecule, and ansible-test each do?Intermediate
30-second answer
In layers: Static— yamllint,ansible-playbook --syntax-check,ansible-lint (best practices and deprecations); role/playbook integration tests——Molecule (create instance → converge → idempotence → verify → destroy); collection development——ansible-test (sanity, units, integration); environment-level— run against staging's --check --diff and smoke tests.
Deeper answer
ansible-lint --profile production molecule test -s default # Full matrix: dependency → create → converge → idempotence → verify → destroy ansible-test sanity --docker default # run from within the collection directory ansible_collections/ns/name
Common interviewer follow-ups
- What is Molecule's verify written in? By default it uses Ansible itself (assert), but Testinfra and others work too.
Bonus points
Stress the value of idempotence tests and check-mode tests; cover the oldest target OS in the test matrix (#9).
Common wrong answer
“Passing one run counts as testing.”
Q33. Walk through Molecule's workflow and driver choices.Intermediate
30-second answer
A Molecule scenario defines test instances and steps: create the instances → prepare → converge (run the role) → idempotence (run again and require no changed) → verify → cleanup/destroy. Common drivers are Docker/Podman (fast, but no full systemd) or delegated (you create VMs/cloud instances yourself, closest to production).
Deeper answer
# molecule/default/molecule.yml (illustrative; check field names against the docs for your Molecule version)
driver:
name: podman
platforms:
- name: ubuntu2404
image: docker.io/library/ubuntu:24.04
provisioner:
name: ansible
verifier:
name: ansible
Common interviewer follow-ups
- How do you test systemd services in a container? Use an image with systemd plus privileged mode / cgroup mounts, or use the delegated driver with VMs (Part A #35).
- How do you speed up development?
molecule convergeKeep re-running, thenmolecule loginto debug.
Bonus points
Run multiple platforms in parallel with a matrix in CI; align scenarios with the EE.
Common wrong answer
“Molecule is just a lint tool.”
See Lesson 2 Module 7.
Q34. A playbook fails in production. What debugging techniques would you use?Intermediate
30-second answer
Read the error type (UNREACHABLE/FAILED/ERROR) → --limit reproduce on a single host → -vvv/-vvvv → debug dump variables with type_debug → --start-at-task/--step → debugger: on_failed interactive debugging → ANSIBLE_KEEP_REMOTE_FILES=1 run the module manually on the remote host.
Deeper answer
- hosts: web debugger: on_failed # on failure, enter the debugger: p task.args / p task_vars['x'] / redo / c / q tasks: [...]
ansible-playbook site.yml --limit web1 --start-at-task "Template nginx config" -vvv ANSIBLE_DEBUG=1 ansible-playbook ... # engine internals debugging; very verbose output
Common interviewer follow-ups
- .retry files? They are not generated by default (retry_files_enabled defaults to False); use
--limit @site.retryto rerun failed hosts.
Bonus points
Stress stopping the bleeding first (roll back / drain traffic) before debugging; clean up retained remote files afterwards (they may contain secrets).
Common wrong answer
“Just add ignore_errors and keep going.”
Q35. How do you speed up Ansible execution?Advanced
30-second answer
Measure first with profile_tasks; then: raise forks, enable pipelining and SSH ControlPersist, narrow gather_subset and enable fact caching, convert loops to list parameters, use async for long tasks, use the free strategy when hosts have no dependencies on each other, cut unnecessary become and delegate, and use job slicing or sharding at scale.
Deeper answer
Every optimization has a cost: higher forks↑ means more memory and jump host pressure (#41, #42); pipelining and requiretty (#7); fact caches can go stale; the free strategy cannot handle dependencies between hosts.
Common interviewer follow-ups
- What is the biggest gain you have achieved from optimizing? Give numbers in your answer: for example, forks going from 5 to 50, and fact gathering dropping from 5 minutes to 30 seconds.
Bonus points
Point out that “doing less work” matters more than “going faster”: only run against changed hosts/roles (tags, limit, event-driven).
Common wrong answer
“Just set forks to 1000.”
See Lesson 7 Module 4.
Q36. How do you use async and poll? What is fire-and-forget?Intermediate
30-second answer
async: N lets a task run in the background on the remote host for up to N seconds; poll: M checks every M seconds. poll: 0 is fire-and-forget: it moves straight to the next task, and later use async_status to check the result. Useful for long tasks that could drop their connection, and for starting several slow operations in parallel.
Deeper answer
- ansible.builtin.command: /opt/app/bin/reindex
async: 7200
poll: 0
register: job
- ansible.builtin.async_status: { jid: "{{ job.ansible_job_id }}" }
register: st
until: st is finished # as of 2.19, prefer the finished/started tests
retries: 240
delay: 30
Common interviewer follow-ups
- What is the difference between async and the free strategy? async backgrounds a single task; free means hosts do not wait for each other.
Bonus points
Mention that async job result files are stored on the remote host ~/.ansible_async, and need cleaning up (the cleanup mode of async_status).
Common wrong answer
“The task result is lost after poll: 0.”
See Lesson 7 Module 5.
Q37. How do you customize a task's success/failure/changed determination? What is the difference between max_fail_percentage and any_errors_fatal?Intermediate
30-second answer
failed_when/changed_when Customize the judgment based on return values; any_errors_fatal: true any single host failure aborts the entire play; max_fail_percentage aborts when the failure ratio in a batch exceeds the threshold (often used with serial for canary rollouts).
Deeper answer
- ansible.builtin.command: /opt/app/bin/healthcheck register: hc failed_when: hc.rc != 0 or 'DEGRADED' in hc.stdout changed_when: false
Common interviewer follow-ups
- Does a failed host still run later tasks? No. It is removed from the rest of the play (its handlers don't run either, #31).
Bonus points
Canary release: serial: [1, "20%", "100%"] + max_fail_percentage: 0.
Common wrong answer
“max_fail_percentage is calculated across the whole inventory” (it is calculated per batch).
Q38. What are callback plugins for? How do you collect run logs and audit trails?Intermediate
30-second answer
Callback plugins respond to events during a run (task start, results, stats) and are used to customize output (stdout_callback: default, yaml-style output, json), timing (profile_tasks, timer), sending notifications or writing to external systems (log platforms, ARA, etc.). AWX/AAP itself collects job events through callbacks and provides auditing.
Deeper answer
[defaults] callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer stdout_callback = ansible.builtin.default callback_result_format = yaml # easier-to-read results (follow the 2.21 config options) log_path = /var/log/ansible/ansible.log
Common interviewer follow-ups
- How do you keep secrets out of logs?
no_log: true; restrict log_path file permissions; redact in callbacks.
Bonus points
Describe how you ship run results to central logging and alert on failed/changed.
Common wrong answer
“You can only read the terminal output.”
See Lesson 7 Module 6.
Scenario 7-1: Design an Ansible CI test pipeline for the team
A monorepo with 15 roles, supporting Ubuntu 22.04/24.04 and RHEL 9. Design a PR pipeline that finishes within 15 minutes.
Key points of the reference answer
- Stage 1 (1 min): pre-commit / yamllint / ansible-lint (pinned version) / syntax-check.
- Stage 2: run Molecule only for changed roles (filtered by path), with a matrix running the three OS images in parallel; include idempotence.
- Stage 3: run
--check --diff, and post the diff as a PR comment. - Run all steps with the same EE image as production; cache collections and images.
- After merge: deploy to staging + smoke tests, then prod after manual approval (Lesson 5).
Scenario 7-2: How do you refactor a shell-based “deploy script”
There is a 400-line bash deploy script that is called by Ansible's script module, reports changed on every run, and is hard to debug when it fails. How would you refactor it?
Key points of the reference answer
- Split the steps into tasks: user/directory → packages → code release (unarchive/git) → config templates → systemd unit → handler restart → health check.
- Use dedicated modules at each step for idempotence and check mode; add creates/changed_when to the commands that remain necessary.
- Move complex logic into custom modules or filters and write unit tests for them.
- Use Molecule to verify idempotence; for rolling releases, use serial + health checks.
Teaching videos (titles and channels verified via YouTube oEmbed)
The videos above were recorded in 2020; Molecule and ansible-lint commands and config formats have changed since, so follow the current official docs.
Official docs
Module 8 · Part B: Security, Platforms and Scenario Design (Questions 39–50)
- Compare Ansible Vault with external secrets management, and design how secrets flow through CI/AWX.
- Explain the architecture and use cases of AWX/AAP, execution environments, and Event-Driven Ansible.
- Be able to answer system design questions on zero-downtime releases, very large scale, drift detection, supply chain security, and working alongside Terraform.
Skim the questions and what they test first; click a row to jump to the details.
Q39. What is Ansible Vault? What is the difference between encrypting a whole file and encrypt_string? What are its limitations?Beginner
30-second answer
Ansible Vault uses AES256 to encrypt whole files or single variable values, so secrets can be stored in Git alongside code. ansible-vault encrypt file encrypts the whole file (you can't see which variables are in it); encrypt_string only encrypts the values, keeping the file structure readable and easy to review. Use vault-id to support multiple passwords (e.g. dev/prod).
Deeper answer
ansible-vault create --vault-id prod@prompt group_vars/prod/vault.yml ansible-vault encrypt_string --vault-id prod@.vp_prod 'S3cr3t' --name db_password ansible-vault rekey --vault-id prod@old --new-vault-id prod@new group_vars/prod/vault.yml ansible-playbook site.yml --vault-id dev@.vp_dev --vault-id prod@/run/secrets/vp_prod
Convention: vault.yml defines vault_db_password, while plain vars.yml has db_password: "{{ vault_db_password }}", which makes grep and review easy.
Common interviewer follow-ups
- Limitations? The password itself must be distributed; rotation requires rekey and resubmission; you can't audit “who read the secret”; decrypted values can end up in logs/diffs (use no_log).
- How do you provide the password in CI? See Part A #47.
Bonus points
Point out that Vault suits small to mid-size setups; at scale, move to an external secrets system (Q40).
Common wrong answer
“Once encrypted, it is fully secure, so the repo can be public.”
See Lesson 2 Module 4.
Q40. How do you integrate Ansible with external secrets management (HashiCorp Vault, Azure Key Vault, AWS Secrets Manager)?Intermediate
30-second answer
Read secrets at runtime through lookup plugins; no ciphertext is stored in the repo: community.hashi_vault.hashi_vault (or vault_kv2_get), the Key Vault lookup from the Azure collection,amazon.aws.secretsmanager_secret / ssm_parameter lookup. Authenticate with managed identities, IAM roles, or OIDC instead of long-lived keys; inject them into AWX/AAP using credential plugins (external secret lookup).
Deeper answer
db_password: "{{ lookup('amazon.aws.secretsmanager_secret', 'prod/myapp/db', region='ca-central-1') }}"
- ansible.builtin.template: { src: app.env.j2, dest: /etc/myapp/app.env, mode: "0600" }
no_log: true
diff: false
Check each collection's current docs for lookup names and parameters (modules and plugins may be renamed).
Common interviewer follow-ups
- Where does lookup run? On the control node, so the control node/EE needs the matching SDK and identity (#27, #46).
- How do you keep secrets off disk? no_log, diff: false, file permissions 0600, and prefer having the application read directly from the secrets system.
Bonus points
EDA in AAP 2.6 also supports external secrets management (HashiCorp Vault, CyberArk, Azure Key Vault, AWS Secrets Manager).
Common wrong answer
“Just put the cloud access keys in group_vars and encrypt them with Vault.”
Q41. Walk through the core objects and architecture of AWX / AAP automation controller.Intermediate
30-second answer
Core objects: organizations, teams, users (RBAC); projects (Git repositories); inventories (static/dynamic sources, smart inventories); credentials (Machine, cloud, Vault, Source Control, etc.; stored encrypted, users never see the plaintext); execution environments; job templates (project + playbook + inventory + credentials + EE + parameters/surveys); workflow templates (chain jobs, approval nodes, failure branches); scheduling and notifications. Execution layer: execution nodes / instance groups (in AAP, the automation mesh distributes jobs to remote nodes).
Deeper answer
Value: centralized audit (who ran what, on which hosts, and when), credential isolation, self-service (surveys), API integration (ITSM, CI triggers), scheduling and drift detection. Deployment: AWX is deployed on Kubernetes with the AWX Operator; AAP 2.6 supports containerized install and RPM (the last version to support RPM), and from 2.7 onward only containerized.
Common interviewer follow-ups
- How does CI trigger AWX? Launch a job template through the API/CLI (awx or ansible.controller collection), passing extra_vars.
- A job works locally but fails in AWX? Dependency locations and EE (Part A #45, #46).
Bonus points
Describe job isolation: each job runs in a fresh EE container, stateless and reproducible.
Common wrong answer
“AWX is just a web page that runs ansible-playbook.”
Q42. What is an execution environment (EE)? Why do you need one? How do you build it?Intermediate
30-second answer
Use ansible-builder based on execution-environment.yml to build, and use ansible-navigator to run locally; AWX/AAP uses it to execute jobs.
Deeper answer
Benefits: reproducible (pinned digest), consistent across local/CI/platform, isolation from dependency conflicts (different EEs for different teams, EEs with an older core for legacy systems, #9). The build file version 3 includes images, dependencies (ansible_core, ansible_runner, galaxy, python, system), additional_build_steps, etc. (see Part A #46).
Common interviewer follow-ups
- How are EEs released and upgraded? CI build → scan → push to a private registry / Automation Hub → job templates reference the new tag, validated in staging first.
Bonus points
Treat the EE as “immutable infrastructure for control nodes.”
Common wrong answer
“An EE is a container deployed onto managed nodes.”
See Lesson 2 Module 8.
Q43. What is Event-Driven Ansible? What parts make up a rulebook? Give one scenario.Intermediate
30-second answer
EDA lets Ansible respond to events automatically. ansible-rulebook Running a rulebook: sources (event sources, such as webhooks, Kafka, Alertmanager, cloud events) → rules (condition matching) → actions (run a playbook / job template, emit events, etc.). In AAP, the EDA controller manages rulebook activations.
Deeper answer
- name: Auto-remediate disk full
hosts: all
sources:
- ansible.eda.alertmanager:
host: 0.0.0.0
port: 5000
rules:
- name: Disk usage high
condition: event.alert.labels.alertname == "NodeDiskAlmostFull"
action:
run_job_template:
name: cleanup-disk
organization: Ops
Check the current ansible.eda collection and ansible-rulebook docs for source plugin names and the action fields.
Common interviewer follow-ups
- Risks? False triggers and “automation storms”: you need throttling, deduplication, approval, and a human fallback; actions must be idempotent.
Bonus points
With AAP 2.6: external secrets management,event_splitter and filters that split batched events.
Common wrong answer
“EDA is just a cron job.”
See Lesson 5 Module 5.
Q44. Describe an Ansible CI/CD pipeline. How do you connect to clouds and hosts securely?Advanced
30-second answer
PR: lint → syntax-check → Molecule (changed roles) → staging --check --diff; on merge: deploy to staging → smoke tests → manual approval → prod (serial batches). Authentication: GitHub Actions via OIDC federation to Azure/AWS to get short-lived tokens (no long-lived keys); host access uses a private runner/AWX execution node + short-lived SSH certificates or SSM; secrets are read from the secrets system at runtime.
Deeper answer
CI can run ansible-playbook directly (using the EE image), or call the AWX API so the platform handles credentials and audit; the latter suits multi-team setups better. Safeguards: prod requires approval, branch protection, concurrency locks (the same inventory is not deployed in parallel), deployment records and rollback playbooks.
Common interviewer follow-ups
- Why use OIDC? Tokens are short-lived, trust conditions can be restricted by repo/branch/environment, and there are no keys to rotate.
Bonus points
Mention failure modes: runner network unreachable (#1), world-writable (#49), locale (#50), Vault password (#47).
Common wrong answer
“Just store the SSH private key and cloud AK/SK in CI secrets.”
Q45. Design a zero-downtime rolling release implemented with Ansible.Advanced
30-second answer
serial Batches (start with 1 canary host) + max_fail_percentage: 0; per host: pre_tasks inside delegate_to take it out of the load balancer and wait for connections to drain → deploy the new version → handler restart and flush → uri + until health check → post_tasks add it back to the LB. Run database migrations beforehand and keep them backward compatible; on failure, rescue rolls back that host and stops subsequent batches.
Deeper answer
- hosts: app
serial: [1, "30%", "100%"]
max_fail_percentage: 0
pre_tasks:
- name: Drain
community.general.haproxy: { state: disabled, host: "{{ inventory_hostname }}", backend: app, wait: true, drain: true }
delegate_to: "{{ item }}"
loop: "{{ groups['lb'] }}"
roles: [myapp]
post_tasks:
- ansible.builtin.meta: flush_handlers
- ansible.builtin.uri: { url: "http://{{ ansible_host }}:8000/healthz" }
register: hc
until: hc.status == 200
retries: 30
delay: 2
- name: Enable
community.general.haproxy: { state: enabled, host: "{{ inventory_hostname }}", backend: app }
delegate_to: "{{ item }}"
loop: "{{ groups['lb'] }}"
Check the community.general docs for haproxy module parameters; cloud load balancers can be handled with the matching collection modules.
Common interviewer follow-ups
- When do handlers run under serial? They run at the flush point of each batch, so call flush_handlers before the health check.
- Rollback? Keep the previous version directory/symlink to switch back to (or image tags), and switch back in rescue.
Bonus points
Point out how this compares with Kubernetes rolling updates, and when apps should move to an orchestration platform (Lesson 6 Module 7).
Common wrong answer
“Restart the service on all hosts at once.”
Q46. How do you manage 5000+ servers with Ansible?Advanced
30-second answer
Inventory: dynamic inventory + grouping by region/role/environment; execution: multiple AWX/AAP execution nodes (instance groups/mesh for nearby execution) + job slicing, with reasonable forks; performance: pipelining, ControlPersist, fact caching, trimmed facts, async; connectivity: scale out jump hosts or use managed channels such as SSM; run modes: scheduled jobs for baselines or ansible-pull, and use on-demand jobs for changes; governance: unified EE dependencies, RBAC, auditing, and batched rollouts.
Deeper answer
Capacity planning: each execution node's forks are limited by memory (#41); jump host MaxStartups (#42); work backward from the job duration target (e.g. patching within 30 minutes) to the required concurrency and node count; automatically generate reports for failed hosts and retry them.
Common interviewer follow-ups
- What are Ansible's weaknesses at scale? The push model's connection overhead and control node resource usage; it is not good at continuous convergence, so it needs to be paired with scheduling or a pull model.
Bonus points
Give measured data and monitoring metrics (job duration, failure rate, execution node capacity).
Common wrong answer
“Just crank up forks on one control node.”
Q47. How do you do configuration drift detection and compliance with Ansible?Advanced
30-second answer
Prerequisites: the playbook is idempotent and can run in check mode. Run it on a schedule (AWX scheduling) against production with --check --diff, treating changed tasks as drift; send results through callbacks/notifications to tickets or dashboards; choose auto-remediation (real run) or manual approval per policy. Compliance baselines (such as CIS) are implemented as roles, reporting the status of each item.
Deeper answer
Caveats: command/shell are skipped in check mode and need to be marked check_mode: false as read-only probes (#32); diffs containing secrets must be turned off; sources of noise (non-idempotent tasks, #26) must be removed first, otherwise the drift report loses its meaning.
Common interviewer follow-ups
- How is it different from Terraform plan? Ansible only checks the configuration you wrote; resources you didn't write won't be detected. Terraform only manages resources in its state.
Bonus points
Use EDA to detect and remediate in real time events where “someone changed something by hand.”
Common wrong answer
“A full real run on a schedule counts as drift detection” (there is no report, and it can cause unexpected changes).
Q48. How do you harden Ansible itself, including supply chain security?Advanced
30-second answer
Identity: dedicated deployment account, key/certificate auth, minimal sudo rights, host key checking not disabled; secrets: Vault/external secrets system,no_log, disable diff; platform: AWX RBAC, credential isolation, audit logs; supply chain: pin collection and role versions, use a private Automation Hub, collection signature verification (the ansible-galaxy collection install signing options and ansible-galaxy collection verify), EE image scanning and signing; code: review, lint, and never render templates from untrusted sources (2.19 template trust).
Deeper answer
Risk examples: ansible.cfg placed in a world-writable directory (#49); third-party roles executing arbitrary commands; logs leaking secrets; allow_world_readable_tmpfiles; disabling host key checking enables man-in-the-middle attacks (#3).
Common interviewer follow-ups
- What does it mean if the control node is compromised? It effectively gets access to every host; the control/execution nodes are the highest-value assets and need isolation and monitoring.
Bonus points
Tie control node security to the AWX credential model of “use but never reveal.”
Common wrong answer
“Ansible is agentless, so there's no attack surface.”
Q49. How do you combine Terraform and Ansible in the same pipeline?Advanced
30-second answer
Terraform creates the infrastructure and tags resources (Role, Env); Ansible uses dynamic inventory to discover hosts by tag and configure them. Ways to connect: tags + aws_ec2/azure_rm dynamic inventory (recommended, loosely coupled); or read Terraform outputs to generate an inventory; or use only minimal cloud-init bootstrapping in Terraform and leave the rest to Ansible.
Deeper answer
Pipeline: terraform plan/apply → wait for hosts to be ready (wait_for_connection,cloud-init status --wait, #33) → ansible-playbook (same EE, same OIDC identity) → smoke tests. Not recommended: calling Ansible from Terraform via local-exec, since failures are hard to retry and the state gets coupled.
Common interviewer follow-ups
- Immutable route? Bake images with Packer + Ansible; Terraform only swaps image versions.
Bonus points
Explain the boundary: resource lifecycle belongs to Terraform, OS/application configuration to Ansible; avoid having both manage the same attribute.
Common wrong answer
“Use only Ansible's cloud modules, or only Terraform's provisioners.”
See Lesson 3 Module 6; for the Terraform side, see Terraform 8-hour course.
Q50. A production playbook run failed on half the hosts. How do you handle it?Advanced
30-second answer
First stop the bleeding: confirm the business impact; stop the job, roll back, or drain failed hosts from traffic if needed; then locate: check PLAY RECAP to tell unreachable from failed, and trace the execution chain from Part A (connection → rendering → module),--limit limit to failed hosts + -vvv to reproduce; after the fix, rerun on the failed hosts (--limit @retry or AWX “relaunch failed hosts”) to rerun and confirm idempotence; finally a post-mortem: why serial/max_fail_percentage did not stop it, and why tests did not cover it.
Deeper answer
Prevention: batched releases and failure thresholds, check-mode rehearsal, Molecule, automatic rollback with block/rescue, handler force_handlers flush (to avoid “config changed but not restarted,” #31), job notifications and audit.
Common interviewer follow-ups
- Some hosts changed and some didn't; how do you ensure consistency? Rely on idempotence: after the fix, rerun against all targets; steps that aren't idempotent need extra state checks.
Bonus points
Tell a real case and give the improvement items the post-mortem produced (for example, a check that was added to CI).
Common wrong answer
“Rerun everything on all hosts right away and see.”
Scenario 8-1: Design an Ansible platform for a 200-person engineering organization
12 product teams each write their own playbooks, credentials are scattered across personal computers, and production changes have no audit trail. Design the platform (tools, organization, process, security) and describe a phased rollout plan.
Key points of the reference answer
- Platform: AAP 2.6 (or AWX) + private Automation Hub + standard EEs; map organizations/teams to RBAC; centralize credentials and connect them to an external secrets system.
- Content: the platform team maintains base collections (acme.platform) and EEs; product teams maintain application roles and contribute via PRs.
- Process: Git + CI (lint/Molecule/check) → job templates → prod requires workflow approval; scheduled drift detection; EDA handles common alerts.
- Security: host access through execution nodes + short-lived credentials; audit logs sent to SIEM; collection signing and EE scanning.
- Phases: pilot with 2 teams → migrate credentials → roll out templates and training → measure (change lead time, failure rate, MTTR).
Scenario 8-2: Automated alert remediation
The on-call team handles about 50 “disk usage > 90%” alerts a week, with fixed steps (clean old logs, compress, expand if needed). How do you automate this with EDA without causing mistakes?
Key points of the reference answer
- Alertmanager → EDA source; the rule matches the alert name and labels (environment, role).
- Action: run the “diagnose + safe cleanup” job template first (idempotent, deletes only files that match policy); if it fails or usage is still over the threshold, open a ticket and notify a human instead of auto-expanding.
- Safeguards: throttling (at most once per host per hour), applies only to whitelisted groups, prod requires an approval node, and all actions are audited.
- Metrics: auto-remediation rate, false-trigger count; review the rules regularly.
Scenario 8-3: Secrets leak incident
The security team finds a plaintext database password in CI logs, from an Ansible task's -vvv output. How do you respond and prevent it?
Key points of the reference answer
- Response: rotate the password immediately; delete/seal the related logs and artifacts; assess the scope of access.
- Root cause: the task lacks
no_log; CI defaults to -vvv; template diff output. - Prevention: sensitive tasks
no_log: true,diff: false; CI does not enable high verbosity by default; custom lint rules check tasks that use secret variables; switch secrets to runtime lookup; add key-pattern scanning to the log platform.
Teaching videos (titles and channels verified via YouTube oEmbed)
No verified video specifically covering Event-Driven Ansible, execution environments or AAP 2.6 was found; please refer to the official Red Hat docs.
Official docs
Question cheat sheet + interview flashcards
A · Cheat sheet of 50 production issues
Type a keyword to filter (for example sudo,undefined,boto3,vault). Click a number to jump to the matching module's details.
B · 50 interview question flashcards
Try to answer from the question first, then expand to compare with the one-line key point; for details, go back to the “Question details” in the matching module.
General command cards
Connection and privilege escalation
ansible HOST -m ping -vvvv 2>&1 | grep -E 'USER:|SSH: EXEC'
ansible-inventory --host HOST | jq '{ansible_host,ansible_port,ansible_user}'
ssh -v -p PORT USER@IP true
ansible HOST -m command -a 'sudo -n -l'
ansible HOST -m raw -a 'command -v python3; python3 -V'Variables and templates
ansible-playbook site.yml --syntax-check
ansible HOST -m debug -a 'msg={{ [x, x | type_debug] }}'
ansible-inventory --graph --vars
ansible-playbook site.yml --list-tasks --tags TAG
grep -rnE 'when:.*\{\{' roles/Modules and dependencies
ansible-galaxy collection list NS.NAME ansible-config dump --only-changed ansible-doc NS.NAME.MODULE | head ANSIBLE_KEEP_REMOTE_FILES=1 ansible HOST -m MODULE -vvv ansible-playbook site.yml --check --diff --limit HOST
Scale, platform and CI
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks ansible-playbook site.yml ansible-inventory -i INV --graph -vvv ansible-navigator exec --eei EE -- ansible-galaxy collection list head -1 group_vars/prod/vault.yml ansible --version | grep 'config file'; locale
Recommended project-level ansible.cfg snippet
[defaults] inventory = inventories/staging forks = 30 gathering = smart fact_caching = ansible.builtin.jsonfile fact_caching_connection = .cache/facts fact_caching_timeout = 86400 callbacks_enabled = ansible.posix.profile_tasks interpreter_python = auto_silent collections_path = ./collections:~/.ansible/collections [ssh_connection] pipelining = True ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30
Comprehensive drills + mock interview
I. Comprehensive fault drills
Each scenario combines several issues from Part A. Write down your first diagnostic command and your judgment before expanding the answer.
Scenario 1: 20 newly created Azure VMs: half of the hosts fail on the first run of site.yml
fatal: [vm07]: FAILED! => {"msg": "Failed to lock apt for exclusive operation: ... It is held by process 1880 (unattended-upgr)"}
fatal: [vm12]: UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: andy@10.20.1.12: Permission denied (publickey).", "unreachable": true}
$ ansible-inventory --host vm12 | jq .ansible_user
null
Answer: Two issues stacked: on first boot, unattended-upgrades holds the apt lock (#33), so the first play waits cloud-init status --wait, apt sets lock_timeout and retries; the group that vm12 belongs to has no ansible_user, so the local username andy was used (#2). Set it in group_vars ansible_user: azureuser.
Scenario 2: After upgrading the AWX EE to ansible-core 2.21, nightly jobs fail widely
fatal: [web3]: FAILED! => {"msg": "Conditional result was 'True' of type 'str', which evaluates to True. Conditionals must have a boolean result."}
fatal: [legacy01]: FAILED! => {"module_stderr": "... SyntaxError: invalid syntax ...", "msg": "MODULE FAILURE ..."}
Answer:① Stricter conditionals since 2.19 (#18): change the string conditions to | bool, and during the transition you can temporarily enable it for a single project by setting allow_broken_conditionals; ② legacy01's Python is below the 2.21 requirement for managed nodes (#9): upgrade its Python, or keep an EE with an older core for legacy hosts and plan a decommission. Lesson: test EE upgrades against all job templates in staging first.
Scenario 3: The nginx config has been updated, but production still shows the old behavior; the last job run in history shows “failed”
TASK [nginx : Template site config] changed: [web1] TASK [nginx : Verify upstream reachable] fatal: [web1]: FAILED! ... PLAY RECAP web1 : ok=8 changed=1 failed=1 (re-run today) TASK [nginx : Template site config] ok: [web1] ← no RUNNING HANDLER
Answer: The handler was swallowed by a later failure; on re-run the file already has the new content, so it no longer notifies (#31). Reload by hand right away (or trigger it with --force-handlers a change); long term, set it in the play force_handlers: true, put validation tasks after flush_handlers, and add validate.
Scenario 4: Deploying to prod fails in CI, while the same command succeeds locally
[WARNING]: Ansible is being run in a world writable directory (/builds/infra/ansible), ignoring it as an ansible.cfg source. ERROR! the role 'acme.platform.base' was not found ... (after fixing the issue above) ERROR! Attempting to decrypt but no vault secrets found
Answer: A world-writable directory caused the project's ansible.cfg to be ignored (#49), so collections_path has no effect and roles cannot be found. Fix: chmod o-w . or ANSIBLE_CONFIG. Next, it exposes that the Vault password was not supplied (#47): write it from a CI secret to a temp file and --vault-id prod@file.
Scenario 5: Deployment job on AWS: the inventory is empty, but the job reports “success”
[WARNING]: Unable to parse /runner/project/inventory/ec2.yml as an inventory source [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: Could not match supplied host pattern, ignoring: role_web PLAY [role_web] skipping: no hosts matched
Answer: The dynamic inventory file name is not *.aws_ec2.yml (#44), and boto3 may also be missing (#27/#46). Rename it to prod.aws_ec2.yml,plugin: amazon.aws.aws_ec2, the EE must include boto3; assert at the start of the job groups['role_web'] | length > 0, to avoid “succeeding against zero hosts.”
Scenario 6: The PostgreSQL role fails on a new database host
fatal: [db2]: FAILED! => {"msg": "Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: ...)"}
(after installing acl) fatal: [db2]: FAILED! => {"msg": "Failed to import the required Python library (psycopg2) on db2's Python /usr/bin/python3. ..."}
Answer:become_user: postgres Needs acl (#10); the community.postgresql modules run on db2 itself, so db2 needs python3-psycopg2 (#28). Put these two packages in the first group of tasks in the database role (or in the base image).
Scenario 7: The weekly patching job keeps getting slower, and the last two runs ended with Error
Gathering Facts ----------------------------- 1214.33s ERROR! A worker was found in a dead state $ grep -c 'kex_exchange_identification' job_4711.log 63
Answer: Fact gathering is too slow (possibly a stale NFS mount, #40) → someone raised forks too high → execution node memory runs out (#41) and the jump host's MaxStartups drops connections (#42). Fix: gather_subset: ['!hardware'] + fact caching; set forks based on memory and use job slicing; scale out the jump host; run patch tasks with async (#43).
Scenario 8: The Prometheus alert rules rendered from the template are missing labels, and some host configs contain the literal {{ inventory_hostname }}
fatal: [mon1]: FAILED! => {"msg": "AnsibleError: template error while templating string: unexpected char '$' at 3. ..."}
(another place) /etc/myapp/labels.conf: host={{ inventory_hostname }}
Answer: In the alert rules, the {{ $labels.x }} conflicts with Jinja2 (#21): use {% raw %} or switch to copy. labels.conf content comes from an API return value, and since 2.19+ untrusted strings are no longer rendered (#19): pass the value in as a variable to a trusted template in the role's templates/ directory.
II. Full mock interview (10 questions drawn from 50)
Each question has a 2-minute countdown: answer out loud first (you can jot key points in the text box), then expand the reference answer and self-assess as “got it / partial / missed.” When finished, the round's score is shown, along with cumulative mastery rates by module. Self-assessment results are saved in this browser.
III. Open-ended self-test (6 questions)
1. Use one diagram to explain every step of a task from the control node to the managed node, and mark where UNREACHABLE and FAILED separate.
Reference diagram 1-1: TCP → SSH authentication (failure is UNREACHABLE) → temp directory → transfer → become → Python execution (failure is usually FAILED; since 2.19, become timeouts are the exception).
2. You inherit a project where every run reports changed=40. How do you make it idempotent within two weeks?
First use Molecule or two consecutive runs to list the non-idempotent tasks; fix them per #26 and #36 (dedicated modules, creates, changed_when, regex corrections); add an idempotence gate in CI; finally enable check-mode drift detection.
3. What is the checklist for upgrading a major ansible-core version?
Read the porting guide (2.19 template engine); confirm the Python requirements for control and managed nodes; collection compatibility; run lint + Molecule + staging check in a new EE; keep the old EE for rollback.
4. Compare when to use Ansible Vault, an external secrets system, and AWX credentials.
Vault: small teams with no external dependencies; external secrets system: centralized rotation, audit, short-lived credentials; AWX credentials: “use but never see” inside the platform, and they can connect to external secrets lookups. Production usually combines them.
5. Design a plan to patch 3000 hosts within 30 minutes.
Partitioned parallelism (job slicing / multiple execution nodes), forks set by memory, async patching, reboot module, serial + failure threshold, jump host / SSM capacity, pre-change snapshots and a post-change verification report.
6. “Works locally, fails in AWX”: what is your troubleshooting order?
Project sync logs → dependency file locations (#45) → EE contents (#46) → credential injection → network reachability (execution node to hosts) → reproduce locally with ansible-navigator + the same EE.
IV. Final quiz (12 questions)
Sources and version notes
Official documentation sources
| Topic | Conclusion used in this lesson | Source (accessed 2026-11-15) |
|---|---|---|
| Versions and support | core 2.21 (GA 2026-05, EOL 2027-11), 2.20, 2.19 (EOL 2026-11); the community package 14.x is based on core 2.21; 2.21 control node Python 3.12–3.14, managed nodes 3.9–3.14 | Releases and maintenance |
| 2.19 template engine | Conditionals must be boolean (original error text “Conditionals must have a boolean result”),ALLOW_BROKEN_CONDITIONALS transition period; template delimiters are not supported in conditions; template trust: untrusted strings are returned as-is and silently by default; can be _ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR changed to warning/error; become timeouts are classed as unreachable; the bool filter deprecation warning is planned to become an error in 2.23; async_status uses the finished/started tests | ansible-core 2.19 Porting Guide |
| Connection and privilege escalation | ssh plugin, host key checking, sshpass; temp file permissions for become and unprivileged users | ssh connection · Privilege escalation |
| Interpreter discovery | auto / auto_silent; ansible_python_interpreter | Interpreter Discovery |
| SSM connection plugin | amazon.aws.aws_ssm (originally from community.aws 1.0.0); requires session-manager-plugin and an S3 bucket for file transfer | amazon.aws.aws_ssm |
| Windows | WinRM/PSRP depend on Python libraries on the control node; certificate validation | Windows Remote Management |
| Variables, templates, loops, reuse | Variable precedence; Jinja2; migrating loops from with_X; import vs include | Variables · Loops · Re-use |
| Handlers, check/diff, error handling | Notification and flush timing, force_handlers; check-mode limitations; block/rescue | Handlers · Check mode · Error handling |
| Performance and strategy | forks, strategy, serial, async/poll, fact caching | Strategies · Async |
| Configuration | ansible.cfg lookup order; world-writable directories are ignored; config options | Configuration Settings |
| Vault | vault-id, encrypt_string, client scripts | Vault guide |
| Module development and debugging | AnsibleModule, check mode, AnsiballZ explode/execute, ansible-test | Developing modules · Debugging modules · Testing |
| Toolchain | ansible-lint profile, Molecule, ansible-builder v3, ansible-navigator, ansible-rulebook, AWX Operator (specific tool versions are not pinned in this lesson) | Lint · Molecule · Builder · Navigator · Rulebook |
| AAP 2.6 | EDA supports external secrets management, event_splitter; 2.6 is the last version to support RPM installation (RHEL 9); from 2.7 only containerized installation | Red Hat AAP docs |
Video verification note
All videos were verified on 2026-11-15 via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) to check titles and channel names. oEmbed does not return duration or publish date, so these are not shown on the page. Verified: Jeff Geerling's “Ansible 101” series, Episode 1 (goclfp6a2IQ), 2 (7kVfqmGtDL8), 5 (HU-dkXBCPdU), 6 (JFweg2dUvqM), 7 (FaXVZ60o8L8), 8 (CYghlf-6Opc), 9 (gV_16dU7XjM), 10 (iKmY4jEiy_A), 11 (_rDzMYp-fBs), 13 (nyXDR4RG4A8), 14 (N7tgLVCXup4), 15 (sb5XYD3BLMA) (video IDs taken from the author's blog series page); Fireship's “Ansible in 100 Seconds” (xRMPKQweySE); NetworkChuck's “you need to learn Ansible RIGHT NOW!! (Linux Automation)” (5hycyr-8EKs); TechWorld with Nana's “What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners” (1id6ERvfozo); Techno Tim's “Automate EVERYTHING with Ansible! (Ansible for Beginners)” (w9eCU4bGgjQ). The Ansible 101 series was recorded in 2020; follow the current official docs for version details. Not found No verified video specifically on production Ansible troubleshooting, the ansible-core 2.19 template engine, EDA or Ansible interview questions was found; the related sub-pages provide storyboard scripts instead. This courseware cannot directly generate videos or MP3 files.
Audio note
The Audio tab uses the browser's built-in Web Speech API and uploads no data. It requires a Chinese (zh-CN) voice pack installed on the system; without one, read the script directly or pass it to another TTS tool.
Known limitations
- Error message wording follows common ansible-core 2.18–2.21 messages; many errors (undefined, conditionals, templates) were reworded from 2.19 onward, and the display format of error prefixes has also changed. Entries are marked “check against the actual output.”
- All “Sample output” blocks are illustrative: hostnames, IPs, paths, PIDs, times, version patch numbers and so on will differ in your environment. The reproduction labs are written from the official docs and have not been run step by step on every version.
- Details marked “check the official docs” include: the specific err in parentheses in become/unprivileged user errors, the msg for interpreter discovery when there is no Python, the specific requirements for Windows OpenSSH support, the 2.19 untrusted template warning wording,
reconnection_retries, Molecule configuration fields, ansible-builder base images, ansible.eda source plugin names, lookup names and parameters for each cloud collection, haproxy module parameters, and Mitogen compatibility. - The specific latest version numbers of the Ansible community package, ansible-lint, Molecule and AWX are not pinned in this lesson; the role/collection versions in examples (such as geerlingguy.docker 7.4.1) are for illustration only.
- Self-assessment records from the mock interview are stored only in this browser's localStorage and will be lost if site data is cleared.