Ansible Hour 7: Deep Troubleshooting, Optimization and Advanced Topics
- Build a layered troubleshooting methodology: inventory → connection (SSH) → privilege escalation (become) → module (remote Python execution) → templating (Jinja2 rendering). When you see an error, decide within 30 seconds which layer it belongs to, then confirm it with the matching
-vvvvsnippet,ANSIBLE_DEBUGandANSIBLE_KEEP_REMOTE_FILESconfirm. - Master the playbook debugger (
debugger:keywords,p task.args,task_vars+update_task,redo), as well asassert,--step,--start-at-task,--list-tasksand other “narrow-the-scope” tricks. - Dig deeper into connection and privilege issues: ControlPersist, host keys, sudo passwords,
requiretty, non-privileged user temp-file permissions, and Python interpreter discovery. - Use data to drive performance tuning: forks, pipelining, fact caching (jsonfile / redis),
gather_subset, disabling unnecessary facts, and useansible.posix.profile_tasks/timercallbacks to quantify the effect. - Understand execution strategies (linear / free / host_pinned),
throttleandasync+poll+async_status, and know how they change the execution timeline. - Configure callback plugins and auditing: stdout callback, JSON output,
log_path, ARA records every run. - Write and test custom modules, filter and lookup plugins, put them in a collection, and use
ansible-test sanityto check. - Complete the 8 randomly injected faults in the fault mystery box challenge, and produce a performance report with a “before vs. after optimization timing comparison.”
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (3 sshd containers node1–node3) |
|---|---|---|---|---|---|
| 0 | Pre-class | Preparation: fault-injection environment | Rebuild node1–3, the project directory, the “scaled-up inventory” of 30 alias hosts, and the fault-injection script faults.sh | Environment self-check list | ansible all -m ping All green |
| 1 | 00–06 | Troubleshooting methodology and -vvvv | Five-layer localization; what each level from -v to -vvvvvv adds; ANSIBLE_DEBUG; ANSIBLE_KEEP_REMOTE_FILES and AnsiballZ explode/execute | Layer locator: click an error → highlighted layer and evidence | Keep the remote module file and run it manually |
| 2 | 06–14 | Playbook debugger and debug tips | debugger: five values,debug strategies, p/task.args/task_vars/u/r/c/q,assert,--step/--start-at-task | In-browser debugger terminal (command input) | Fix parameters on the failed task in place, then redo |
| 3 | 14–22 | Deep dive into connection and privilege issues | SSH parameters and ControlPersist, host key, become methods and sudo password, requiretty, non-privileged become temp files, interpreter discovery | Break down the SSH command of one task (explain each parameter) | Reproduce and fix 4 connection/privilege-escalation faults |
| 4 | 22–31 | Performance: forks, pipelining, fact caching | forks concurrency model, pipelining principles and prerequisites, fact caching,gather_subset, profile_tasks/timer | Core animation: SSH round-trips before and after pipelining + forks timeline | Timing of the same playbook over 4 tuning rounds |
| 5 | 31–38 | Execution strategies and async/poll | linear / free / host_pinned,serial and throttle, async long-running tasks,poll: 0 + async_status | Core animation: forks × strategy execution timeline simulator | free strategy comparison + parallel long-running tasks |
| 6 | 38–44 | Callback plugins and log auditing | stdout callback and result_format,ansible.posix.json/jsonl,log_path,no_log, ARA | Output switching for the same run under 5 callbacks | JSON output + jq statistics + ARA records |
| 7 | 44–52 | Custom modules, filters and plugins | AnsibleModule skeleton, check_mode/diff, filter and lookup plugins, collection layout,ansible-test sanity | Module execution lifecycle (AnsiballZ packaging → JSON return) | Write lab.ops.app_release a module + 2 plugins |
| 8 | 52–60 | Mixed fault mystery box | 8 randomly injected faults; localize with the five-layer method; interactive troubleshooting tree | In-browser fault simulator (draw questions, enter diagnostic commands, timer) | faults.sh random Real mystery box |
| — | Post-class | Cheat sheet · Comprehensive lab | Fault mystery box challenge + performance optimization report (before/after timing of the same playbook) | Final quiz, 12 questions | Comprehensive lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / configuration | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Localize faults by layer | ✓ | ✓ | ✓ | · | · | · | · | ✓ | -vvvv,ansible-inventory --graph | M1, mystery box |
| View the remote module and raw return | ✓ | · | · | · | · | · | ✓ | · | ANSIBLE_KEEP_REMOTE_FILES=1,explode | M1 lab |
| Interactive debugging | · | ✓ | · | · | · | · | · | ✓ | debugger: on_failed,redo | M2 lab |
| SSH / ControlPersist / host key | ✓ | · | ✓ | ✓ | · | · | · | ✓ | ssh_args,ssh-keygen -R | M3 lab |
| become and temp-file permissions | ✓ | · | ✓ | ✓ | · | · | · | ✓ | -K,acl,pipelining | M3 lab |
| Performance measurement and tuning | · | · | · | ✓ | ✓ | ✓ | · | · | profile_tasks,forks,fact_caching | M4 lab, performance report |
| Execution strategies and async | · | · | · | ✓ | ✓ | · | · | · | strategy: free,async_status | M5 lab |
| Callbacks, logging and auditing | · | · | · | ✓ | · | ✓ | · | · | stdout_callback,log_path, ARA | M6 lab |
| Extending Ansible (modules/plugins) | · | · | · | · | · | · | ✓ | · | AnsibleModule,ansible-test sanity | M7 lab |
Topics excluded from this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn it |
|---|---|---|
| Reproducing 50 production issues one by one, interview questions | This lesson covers methods and tools; the issue list is in the optional Lesson 8 | Hour 8 |
| AWX / AAP job logs, Automation Analytics | Platform-side observability was covered in Lesson 5 | Hour 5 |
| Windows (WinRM/PSRP/SSH) connection troubleshooting | All managed nodes in this lesson are Linux containers | Official Windows guide |
| Third-party accelerators such as Mitogen | Unofficial project; compatibility with newer ansible-core versions must be assessed on your own | Project's own documentation |
| Molecule scenario testing, ansible-lint rules | Covered in Lesson 2; this lesson only uses ansible-test sanity Inspect plugin code | Hour 2 |
| Network devices (network_cli / netconf) persistent connections | Different connection model (persistent connection), beyond the 1-hour scope | Network Debug and Troubleshooting Guide |
How to use this courseware
Concepts · diagrams · animation · commands · lab · production cases · troubleshooting · quiz · audio · video. This is a troubleshooting lesson; for each module, read the raw error text on the "Troubleshooting" page first, then return to the concepts.
A quiz score of ≥ 70%, or clicking "Mark this module complete", counts toward progress. Progress is saved in this browser (it is cleared on refresh when local storage is blocked).
The "Audio" page reads the lecture script aloud using the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
profile_tasks,timer,json,jsonl Callbacks are located in ansible.posix collection (2.2.x); the built-in oneline,tree callbacks are marked as deprecated; community.general.yaml callback was removed in community.general 12.0.0; use the default callback's result_format=yaml.Module 0 · Preparation: fault-injection environment (complete before class)
- Completed Lessons 1 through 6; control node is Ubuntu 24.04 (Azure VM or local machine), with Docker Engine 29 installed, and
pipx install --include-deps ansibleinstalled the Ansible community package 14.x (including ansible-core 2.21). - The managed-node containers built in Lesson 1 Module 0
node1–node3(running sshd on Ubuntu 24.04), with SSH ports mapped to host ports 2221–2223, logging in as useransible, key~/.ssh/ansible_lab, passwordless sudo. If they have been deleted, rebuild them using Step 2 below. - The Lesson 6 myapp multi-tier deployment is not required: this lesson uses a separate project directory
~/ansible-lab/part7, so fault injection does not break the results of Lesson 6.
Step 1: check the control node
ansible --version | head -3
python3 --version
ansible-galaxy collection list ansible.posix community.general 2>/dev/null | grep -E 'ansible.posix|community.general'
docker ps --format '{{.Names}}\t{{.Ports}}' | grep node
ansible [core 2.21.6] config file = None configured module search path = ['/home/azureuser/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] Python 3.12.3 ansible.posix 2.2.2 community.general 12.x or later node1 0.0.0.0:2221->22/tcp node2 0.0.0.0:2222->22/tcp node3 0.0.0.0:2223->22/tcp
Use the actual version in your environment. If ansible.posix is missing (when only ansible-core is installed), run ansible-galaxy collection install ansible.posix community.general.
Step 2 (only if the nodes were deleted): rebuild node1–node3
FROM ubuntu:24.04
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
openssh-server sudo python3 python3-apt acl ca-certificates curl \
&& 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 \
&& chmod 0440 /etc/sudoers.d/ansible \
&& useradd -m -s /bin/bash appsvc
COPY ansible_lab.pub /home/ansible/.ssh/authorized_keys
RUN chown -R ansible:ansible /home/ansible/.ssh && chmod 700 /home/ansible/.ssh && chmod 600 /home/ansible/.ssh/authorized_keys
EXPOSE 22
CMD ["/usr/sbin/sshd","-D","-e"]
mkdir -p ~/ansible-lab/part7 && cd ~/ansible-lab/part7 [ -f ~/.ssh/ansible_lab ] || ssh-keygen -t ed25519 -N '' -f ~/.ssh/ansible_lab cp ~/.ssh/ansible_lab.pub . docker build -t ansible-node:24.04 -f Dockerfile.node . for i in 1 2 3; do docker rm -f node$i 2>/dev/null docker run -d --name node$i --hostname node$i -p 222$i:22 ansible-node:24.04 done docker ps --filter name=node
ansible.builtin.systemd/service service-management tasks will fail. This lab deliberately avoids service management and focuses on connection, privilege escalation, performance and plugins. For full systemd behavior, use 3 Standard_B1s Azure VMs or multipass launch 24.04 -n node1, and replace the addresses and ports in the inventory below. The image also creates a non-privileged user appsvc, which Module 3 uses to demonstrate the temp-file problem of "become to a non-privileged user"; the image pre-installs acl, and the fault-injection script will uninstall it when needed.Step 3: project files
[defaults] inventory = inventory/lab.ini forks = 5 host_key_checking = True interpreter_python = auto_silent retry_files_enabled = False # Opened step by step in this lesson: callbacks_enabled, fact_caching, log_path, strategy … [ssh_connection] # Default values: -C -o ControlMaster=auto -o ControlPersist=60s ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s pipelining = False
[web] node1 ansible_port=2221 node2 ansible_port=2222 [db] node3 ansible_port=2223 [lab:children] web db [lab:vars] ansible_host=127.0.0.1 ansible_user=ansible ansible_ssh_private_key_file=~/.ssh/ansible_lab
Performance experiments need more "hosts". Three containers are not enough to show the effect of forks, so we use aliases to map the 30 inventory hosts onto these 3 sshd servers (10 aliases per container):
[scale] h[01:10] ansible_port=2221 h[11:20] ansible_port=2222 h[21:30] ansible_port=2223 [scale:vars] ansible_host=127.0.0.1 ansible_user=ansible ansible_ssh_private_key_file=~/.ssh/ansible_lab
host:port:user, so the ControlPersist master connection (control socket) is also shared by aliases, which makes the "first connection" cost lower than for 30 real machines. The experiment results are used to compare the relative effects; absolute numbers depend on the real environment (noted under "Known limitations" on the sources page).Step 4: fault-injection script
The script runs on the host, using docker exec to modify containers or project files, simulating 8 common faults; random the subcommand randomly picks one without telling you which,reset and restores. Module 8 and the comprehensive lab use it.
#!/usr/bin/env bash
# Usage: ./faults.sh {list|1..8|random|reveal|reset}
set -euo pipefail
cd "$(dirname "$0")"
N=node2 # default: inject into node2
STATE=.fault # records which fault was injected (not printed for random)
f1(){ mkdir -p host_vars; echo 'ansible_port: 2299' > host_vars/node2.yml; } # inventory layer: wrong port
f2(){ docker rm -f $N >/dev/null; docker run -d --name $N --hostname $N -p 2222:22 ansible-node:24.04 >/dev/null
sleep 2; docker exec $N sh -c 'rm -f /etc/ssh/ssh_host_*; ssh-keygen -A' >/dev/null; docker restart $N >/dev/null; } # connection layer: host key changed
f3(){ docker exec $N sh -c "echo 'ansible:Passw0rd!' | chpasswd; echo 'ansible ALL=(ALL) ALL' > /etc/sudoers.d/ansible"; } # privilege layer: sudo requires a password
f4(){ docker exec $N sh -c 'mv /usr/bin/python3.12 /usr/bin/python3.12.off'; } # module layer: no Python on the remote host
f5(){ docker exec $N sh -c "echo 'Defaults requiretty' > /etc/sudoers.d/00-tty"
sed -i 's/^pipelining = False/pipelining = True/' ansible.cfg; } # privilege layer: requiretty + pipelining
f6(){ docker exec $N sh -c 'apt-get remove -y acl >/dev/null 2>&1 || true'; } # privilege layer: non-privileged become without setfacl
f7(){ docker exec $N sh -c 'chmod 000 /home/ansible/.ansible 2>/dev/null || (mkdir -p /home/ansible/.ansible && chown ansible: /home/ansible/.ansible && chmod 000 /home/ansible/.ansible)'; } # module layer: remote_tmp not writable
f8(){ mkdir -p group_vars; printf 'app_name: myapp\n# app_port was accidentally deleted\n' > group_vars/web.yml; } # templating layer: variable undefined
case "${1:-list}" in
list) grep -E '^f[0-9]\(\)' "$0" | sed 's/{.*#/ #/' ;;
[1-8]) "f$1"; echo "$1" > $STATE; echo "Injected fault $1" ;;
random) k=$(( RANDOM % 8 + 1 )); "f$k"; echo "$k" > $STATE; echo "A random fault was injected; start troubleshooting (./faults.sh reveal shows the answer)" ;;
reveal) echo "Injected fault: $(cat $STATE 2>/dev/null || echo 'none')" ;;
reset)
rm -rf host_vars/node2.yml group_vars/web.yml $STATE
sed -i 's/^pipelining = True/pipelining = False/' ansible.cfg
docker rm -f $N >/dev/null 2>&1 || true
docker run -d --name $N --hostname $N -p 2222:22 ansible-node:24.04 >/dev/null
sleep 2; ssh-keygen -R '[127.0.0.1]:2222' >/dev/null 2>&1 || true
ssh-keyscan -p 2222 127.0.0.1 2>/dev/null >> ~/.ssh/known_hosts
echo "Restored: node2 rebuilt, configuration reset" ;;
esac
chmod +x faults.sh
# Pre-trust the host keys of the 3 nodes (required when host_key_checking=True)
for p in 2221 2222 2223; do ssh-keyscan -p $p 127.0.0.1 2>/dev/null; done >> ~/.ssh/known_hosts
ansible lab -m ansible.builtin.ping -o
ansible scale -i inventory/scale.ini -m ansible.builtin.ping -o | sort | uniq -c | awk '{print $1, $3, $4}' | head -3
node1 | SUCCESS => {"changed": false,"ping": "pong"}
node2 | SUCCESS => {"changed": false,"ping": "pong"}
node3 | SUCCESS => {"changed": false,"ping": "pong"}
30 | SUCCESS
faults.sh This deletes and rebuilds containers, modifies sudoers, and moves Python away,so it must only be run on this lesson's lab containers, and must never be pointed at a real host. f3 The password set here is for demonstration only -K, and after the lab, run ./faults.sh reset.Warm-up: answer from memory (30 seconds)
When a task runs on a managed node, what steps does Ansible actually perform?
The control node renders the parameters → packages the module and module_utils into a self-extracting AnsiballZ Python file → creates a remote temp directory over SSH and transfers the file (sftp/scp, or straight through stdin with pipelining) → sets permissions → runs it with the remote Python (become if needed) → the module prints JSON to stdout → the control node parses the JSON into ok/changed/failed → deletes the remote temp directory. Module 1 will use -vvvv to see every step clearly.
UNREACHABLE and FAILED What is the fundamental difference?
UNREACHABLE means the connection plugin failed (SSH cannot connect, authentication fails, the temp directory cannot be created, etc.) and the module never ran; FAILED means the module ran and returned failed: true (or returned output that could not be parsed). This is the first dividing line of the five-layer method.
Module 1 · Troubleshooting methodology and -vvvv
- Break one task execution into five layers: inventory → connection → privilege escalation → module → templating, and be able to name the typical error and the matching evidence for each layer.
- Know what
-vthrough-vvvveach level adds, and when you needANSIBLE_DEBUG=1. - Use
ANSIBLE_KEEP_REMOTE_FILES=1to keep the remote AnsiballZ file,explodethen run the module directly on the managed node.
What: what is "layered localization"
A single Ansible task execution is a pipeline. Each layer has its own inputs, outputs and failure modes, and the error text usually already reveals which layer it came from:
| Layer | Who does the work | Typical error keywords | Result status | Primary evidence |
|---|---|---|---|---|
| ① Inventory | inventory plugins (ini/yaml/script/auto), variable merging | Could not match supplied host pattern,provided hosts list is empty,Unable to parse … as an inventory source | usually the task never runs at all | ansible-inventory --graph,--host H |
| ② Connection | ssh connection plugin, OpenSSH client, ControlPersist | UNREACHABLE,Connection refused,Permission denied (publickey),Host key verification failed,Connection timed out | UNREACHABLE | -vvvv (including OpenSSH's debug1: line) |
| ③ Privilege escalation (Become) | become plugins (sudo/su/…) | Missing sudo password,Incorrect sudo password,a tty is required,Failed to set permissions on the temporary files | FAILED (rarely UNREACHABLE) | -vvv in the sudo -H -S -n -u root /bin/sh -c 'echo BECOME-SUCCESS-…' |
| ④ Module | remote Python interpreter + AnsiballZ + module code | MODULE FAILURE,/usr/bin/python3: not found,No module named 'apt', the module's own msg | FAILED | -vvv of module_stdout/module_stderr; ANSIBLE_KEEP_REMOTE_FILES=1 |
| ⑤ Templating | Jinja2 / variable resolution on the control node (2.19+ data tagging) | 'x' is undefined,Conditional result was … not a boolean,template error while templating string | FAILED (on the control node; no remote action at all) | debug: var=,ansible-inventory --host,-vvv of Origin: messages |
Note that the order is not exactly the order in which things happen: templating actually happens before the connection (the control node renders task parameters first, then connects). But when troubleshooting, work from the bottom up, following the "check the cheapest things first" principle: inventory (offline check) → connection (ping) → privilege escalation (-b ping) → module → templating.
Why: why a methodology is needed
Jumping straight in -vvvv to run the whole playbook usually produces thousands of lines of output, and the useful information gets buried. The layered method turns the problem into a series of binary questions:
- is UNREACHABLE or FAILED? → separates the connection layer from the layers above it.
ansible H -m pingreachable,ansible H -m ping -bunreachable? → privilege escalation layer.- If nothing at all happens on the remote side (
-vvvhas noSSH: EXEC) and it still fails? → templating/inventory layer; the problem is on the control node. MODULE FAILUREandrc: 127? → remote Python not found;rc: 1and there is a Traceback? → module code or dependency.
How: what each verbosity level outputs
| Level | Main newly added content | Purpose |
|---|---|---|
-v | The complete return value (JSON) of each task, including tasks that are ok | to see the module's returned stdout/msg/diff |
-vv | file and line number of the task (task path: …/site.yml:12), loaded role/include, and the configuration file used | locate “which task in which file” |
-vvv | each step of the connection plugin: ESTABLISH SSH CONNECTION,SSH: EXEC ssh … full command,PUT … TO …, become command, raw module stdout/stderr | the main tool for connection, privilege-escalation and module layers |
-vvvv | On top of -vvv, add to OpenSSH -vvv, output debug1/2/3: handshake details (key exchange, auth methods, ControlMaster reuse) | authentication failures, host keys, ControlPersist, jump hosts |
-vvvvv / -vvvvvv | mainly affects the more detailed logs of some connection plugins (e.g. WinRM/PSRP) | usually not needed for Linux/SSH scenarios |
ANSIBLE_DEBUG=1 (config option DEFAULT_DEBUG) turns on Ansible's own internal debug log: creation of worker processes, queues, locks, plugin loading, etc., with a PID prefix. It is aimed at “Ansible itself misbehaving” (hangs, deadlocks, plugin load order), produces a very large amount of output, and may print sensitive data, so don't keep it on in production CI.
ANSIBLE_KEEP_REMOTE_FILES=1 (DEFAULT_KEEP_REMOTE_FILES) makes Ansible, after execution,not delete the remote ~/.ansible/tmp/ansible-tmp-*/ directory, which contains the self-extracting AnsiballZ_<module>.py. Running python3 AnsiballZ_x.py explode will extract debug_dir/ (module source + args parameter file), after editing, python3 AnsiballZ_x.py execute rerun—this is the standard method for “single-stepping” a module on the managed node.
ANSIBLE_PIPELINING=False.When: what to use when
- Day to day:
-v+--diff; when CI fails, add-vvto get the file line number. - UNREACHABLE: first run
ansible H -m ping -vvvvon its own; do not turn on -vvvv for the whole playbook. - MODULE FAILURE:
-vvvlook atmodule_stderr; still unclear → KEEP_REMOTE_FILES + explode. - Ansible hangs and -vvvv shows no output:
ANSIBLE_DEBUG=1, or on the control nodepy-spy dump --pid(third-party tool) to see where the worker gets stuck.
Comparison with similar techniques
| Ansible | Terraform | kubectl | |
|---|---|---|---|
| verbose logging | -v…-vvvv | TF_LOG=DEBUG/TRACE | -v=6…-v=9 (HTTP request/response) |
| internal debugging | ANSIBLE_DEBUG=1 | TF_LOG_CORE/TF_LOG_PROVIDER | — |
| keeping execution artifacts | ANSIBLE_KEEP_REMOTE_FILES | -out=plan + terraform show -json | --dry-run=server -o yaml |
ANSIBLE_DEBUG is just more v's”—no, it is developer logging, orthogonal to verbosity. ③ “The error is in whichever task reports it”—a templating error may come from a variable overridden in group_vars (variable precedence, see Lesson 2 Module 3); use ansible-inventory --host to see the final value. ④ “UNREACHABLE is always a network problem”—failing to create the remote temp directory (permissions, full disk) also shows up as UNREACHABLE.Architecture diagram: the five-layer pipeline of one task and its evidence points
Decision flow: from one error to one layer
Interaction: layer locator
Click any of the real errors below and the pipeline on the left highlights the layer it belongs to, then steps through “locate → evidence → fix”. The terminal shows the commands you should run and the key output lines. You can also click “Play a normal run” to see each step a successful task goes through under -vvv.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-inventory --graph | Inventory layer: tree of hosts and groups | -i,--vars (show variables) |
ansible-inventory --host H | Final merged variables for a host | Troubleshoot variable precedence and “undefined” |
ansible H -m ping / -b | Minimal verification for the connection / privilege-escalation layers | The ping module needs remote Python; it only verifies that SSH works -m raw -a 'id' |
ansible-playbook … -vvv | Connection, privilege escalation and module details | Used together with --limit H,--start-at-task to narrow the scope |
ANSIBLE_KEEP_REMOTE_FILES=1 | Keep the remote AnsiballZ file | Requires pipelining off; clean up manually afterwards ~/.ansible/tmp |
ANSIBLE_DEBUG=1 | Ansible internal debug log | Huge output; may contain sensitive information |
ansible-config dump --only-changed | Currently effective non-default configuration and its source | -t all includes plugin configuration; ansible-config view see file |
① Inventory layer: offline check
cd ~/ansible-lab/part7 ansible-inventory --graph ansible-inventory --host node2 | head -20 ansible 'web:!node9' --list-hosts
@all:
|--@ungrouped:
|--@lab:
| |--@web:
| | |--node1
| | |--node2
| |--@db:
| | |--node3
{
"ansible_host": "127.0.0.1",
"ansible_port": 2222,
"ansible_ssh_private_key_file": "~/.ssh/ansible_lab",
"ansible_user": "ansible"
}
hosts (2):
node1
node2
How to verify: If --host shows something other than the value you expect ansible_port , the problem is in the inventory/variable layer, and the SSH debugging that follows is wasted effort. Common mistakes: host_vars file name does not match the inventory host name (node2.yaml vs. the name listed in inventory as node2.lab).
② Connection layer: a single host only
ansible node2 -m ansible.builtin.ping -vvvv 2>&1 | grep -E 'ESTABLISH|SSH: EXEC|debug1: (Authenticat|Server host key|auto-mux|Connecting)|UNREACHABLE|pong' | head -20
<127.0.0.1> ESTABLISH SSH CONNECTION FOR USER: ansible
<127.0.0.1> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o Port=2222 -o 'IdentityFile="/home/azureuser/.ssh/ansible_lab"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="ansible"' -o ConnectTimeout=10 -o 'ControlPath="/home/azureuser/.ansible/cp/3f1c0a2b9d"' 127.0.0.1 '/bin/sh -c '"'"'echo ~ansible && sleep 0'"'"''
debug1: Connecting to 127.0.0.1 [127.0.0.1] port 2222.
debug1: Server host key: ssh-ed25519 SHA256:1qJ…
debug1: Authentications that can continue: publickey,password
debug1: Authentication succeeded (publickey).
debug1: auto-mux: Trying existing master
node2 | SUCCESS => { "changed": false, "ping": "pong" }
Note that with -vvvv the command line gains ssh -vvv: this is where OpenSSH's debug1: line comes from. auto-mux: Trying existing master indicates that the ControlPersist master connection was reused (Modules 3 and 4 cover this in detail).
③ Privilege escalation layer
ansible node2 -m ansible.builtin.ping -b -vvv 2>&1 | grep -oE "sudo -H -S -n +-u root /bin/sh -c '\"'\"'echo BECOME-SUCCESS-[a-z]+" | head -1 ansible node2 -m ansible.builtin.command -a 'id' -b -o
sudo -H -S -n -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-qzvmlrkxhbtyeswucnpd node2 | CHANGED | rc=0 | (stdout) uid=0(root) gid=0(root) groups=0(root)
-n (non-interactive) means that when no become password is supplied, sudo does not prompt and fails directly; if -K or ansible_become_password is supplied, Ansible switches to -p "[sudo via ansible, key=…] password:" a custom prompt and writes the password when it sees that prompt. BECOME-SUCCESS-random string is the marker Ansible uses to confirm “privilege escalation succeeded, and the output that follows belongs to the module”.
④ Module layer: keep the remote file and run it manually
ANSIBLE_KEEP_REMOTE_FILES=1 ANSIBLE_PIPELINING=False \ ansible node2 -m ansible.builtin.file -a 'path=/tmp/demo state=touch' -vvv 2>&1 | grep -E 'PUT .*AnsiballZ' docker exec -u ansible node2 sh -c 'ls -d ~/.ansible/tmp/ansible-tmp-*'
<127.0.0.1> PUT /home/azureuser/.ansible/tmp/ansible-local-48213ab12/tmpq8z1k3/AnsiballZ_file.py TO /home/ansible/.ansible/tmp/ansible-tmp-1763201120.53-48230-21944201911870/AnsiballZ_file.py /home/ansible/.ansible/tmp/ansible-tmp-1763201120.53-48230-21944201911870
docker exec -it -u ansible node2 bash cd ~/.ansible/tmp/ansible-tmp-*/ python3 AnsiballZ_file.py explode find debug_dir -maxdepth 3 | head; cat debug_dir/args python3 AnsiballZ_file.py execute exit
Module expanded into:
/home/ansible/.ansible/tmp/ansible-tmp-1763201120.53-48230-21944201911870/debug_dir
debug_dir
debug_dir/ansible
debug_dir/ansible/module_utils
debug_dir/ansible/modules
debug_dir/ansible/modules/file.py
debug_dir/args
{"ANSIBLE_MODULE_ARGS": {"path": "/tmp/demo", "state": "touch", "_ansible_check_mode": false, …}}
{"path": "/tmp/demo", "changed": true, "diff": {…}, "dest": "/tmp/demo", "uid": 1000, …}
How to verify: you can edit directly debug_dir/ansible/modules/file.py add print, or change debug_dir/args parameters in it, then execute. Common mistakes: with pipelining on, the file is not found; forgetting to clean up lets ~/.ansible/tmp filling up (which may contain sensitive parameters!). Production use: When a third-party collection module misbehaves on one particular machine, use it to reproduce the problem on that machine.
⑤ Templating layer and configuration
ansible node1 -m ansible.builtin.debug -a 'msg="port={{ app_port | default(\"UNDEFINED\") }}"'
ansible-config dump --only-changed
ANSIBLE_DEBUG=1 ansible node1 -m ping 2>&1 | head -5
node1 | SUCCESS => {
"msg": "port=UNDEFINED"
}
CONFIG_FILE() = /home/azureuser/ansible-lab/part7/ansible.cfg
DEFAULT_FORKS(/home/azureuser/ansible-lab/part7/ansible.cfg) = 5
DEFAULT_HOST_LIST(/home/azureuser/ansible-lab/part7/ansible.cfg) = ['/home/azureuser/ansible-lab/part7/inventory/lab.ini']
INTERPRETER_PYTHON(/home/azureuser/ansible-lab/part7/ansible.cfg) = auto_silent
48311 1763201188.10811: starting run
48311 1763201188.10897: Added group all to inventory
…
/mnt/c), Ansible ignores the ansible.cfg in it for security reasons and prints a warning. ansible --version The config file = line is the first evidence.Experiment 1: localize one injected fault with the five-layer method (about 6 minutes)
- name: lab site
hosts: web
gather_facts: false
vars:
app_name: myapp
app_port: 8000
tasks:
- name: connectivity
ansible.builtin.ping:
- name: render config (template layer)
ansible.builtin.copy:
dest: /tmp/{{ app_name }}.conf
content: |
name={{ app_name }}
port={{ app_port }}
mode: "0644"
- name: root-only file (become layer)
ansible.builtin.file:
path: /etc/{{ app_name }}.marker
state: touch
mode: "0644"
become: true
- name: run as unprivileged appsvc (become to non-root)
ansible.builtin.command: id -un
become: true
become_user: appsvc
changed_when: false
ansible-playbook site.yml
PLAY RECAP ********************************************************************* node1 : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 node2 : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
./faults.sh 1 ansible-playbook site.yml
fatal: [node2]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host 127.0.0.1 port 2299: Connection refused", "unreachable": true}
UNREACHABLE → looks like a connection-layer problem. But first run the cheapest check:
ansible-inventory --host node2 | grep port grep -rn 'ansible_port' inventory/ host_vars/ group_vars/ 2>/dev/null
"ansible_port": 2299, inventory/lab.ini:2:node2 ansible_port=2222 host_vars/node2.yml:1:ansible_port: 2299
The root cause is in the inventory layer: host_vars takes precedence over the host variables in the inventory file (Lesson 2 Module 3). The connection layer is only the “victim”.
./faults.sh reset ansible-playbook site.yml --limit node2
copy module, open debug_dir/args, and confirm content is already the rendered text. This proves the template was completed on the control node, and the remote module only receives the result.
ANSIBLE_KEEP_REMOTE_FILES=1 ANSIBLE_PIPELINING=False ansible-playbook site.yml --limit node1 --start-at-task 'render config (template layer)' -vvv 2>&1 | grep -m2 'PUT .*AnsiballZ' docker exec -u ansible node1 sh -c 'cd ~/.ansible/tmp && ls -t | head -3'
Tip: copy with content , the action plugin first writes the content to a temporary file and sends that, so you will see more than one PUT (the source file + AnsiballZ_copy.py).
for n in node1 node2 node3; do docker exec -u ansible $n sh -c 'rm -rf ~/.ansible/tmp/ansible-tmp-*'; done ansible web -m ansible.builtin.file -a 'path=/tmp/demo state=absent'
Case 1: 7 of 300 CI hosts are UNREACHABLE
Problem: The overnight patching job had 7 failures, and the on-duty engineer simply changed the whole job to -vvvv rerun, generating 40 MB of logs. Approach: Using the idea of --limit @site.retry (or “rerun only failed hosts” in AWX), target only those 7 hosts, then use ansible FAILED_HOSTS -m raw -a true -vvvv to verify SSH only. It turned out all 7 were Host key verification failed—they had been reinstalled over the weekend. Configuration: Add a step to the reinstall process that updates known_hosts (or use SSH certificates signed by a host-certificate CA). Limitations: Do not use host_key_checking=False as a blanket fix; that would make man-in-the-middle attacks undetectable.
Case 2: a collection module gives MODULE FAILURE on only one host
Problem:community.general A module from the collection reports MODULE FAILURE on 1 RHEL host,module_stderr with only one line of ImportError. Approach: On that host, use KEEP_REMOTE_FILES + explode, then run the module directly in debug_dir , and find that the host's ansible_python_interpreter was wrongly pinned to the old system Python, which lacked the dependency libraries. Configuration: Remove the hard-coded interpreter path from host_vars, switch it back to auto, and install the dependencies in the base image. Limitations: The file left after explode contains module parameters and may include passwords; delete it once troubleshooting is done.
Case 3: all tasks “hang” and -vvvv shows no new output
Problem: A playbook gets stuck at Gathering Facts for 30 minutes. Approach:-vvvv shows SSH connected and the module sent, and then no return → the problem is in remote execution. Logged in to the managed node ps -ef | grep AnsiballZ, and found that the setup module was stuck collecting mount point information (a lost NFS mount). Configuration:gather_subset: ['!hardware'] or set gather_timeout, and fix NFS. Limitations: See the fact optimization in Module 4.
Common errors and fixes
[WARNING]: Could not match supplied host pattern, ignoring: webservers
Layer:① Inventory. Cause: Misspelled group name, wrong inventory in use (ansible.cfg not taking effect), dynamic inventory plugin failed to parse but only warned.
ansible --version | grep 'config file' ansible-inventory --graph ansible-inventory -i inventory/ --list -vvv 2>&1 | grep -iE 'parse|skipping|failed'
Fix: Correct the group name; confirm config file points to the project's ansible.cfg; in CI, set ANSIBLE_INVENTORY_UNPARSED_FAILED=True so that parse failures error out directly.
fatal: [node2]: UNREACHABLE! => {"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. …"}
Layer:② Connection (but the root cause is the remote filesystem). Cause:remote_tmp (default ~/.ansible/tmp) is not writable: wrong directory permissions, home does not exist, disk full, read-only filesystem.
ansible node2 -m raw -a 'id; ls -ld ~ ~/.ansible ~/.ansible/tmp; df -h ~ /tmp'
Fix: Fix permissions or free up disk space; temporarily you can set ansible_remote_tmp=/tmp/.ansible-${USER}. raw The module does not need a temp directory, which makes it the best probe for this kind of problem.
fatal: [node2]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'app_port' is undefined"}
Layer:⑤ Templating (control node). In -vvv, the task before this one has no SSH: EXEC. Cause: Undefined variable, wrong scope (set_fact in another play), group_vars file name does not match the group name.
ansible-inventory --host node2 --yaml | grep -n app_ ansible node2 -m debug -a 'var=app_port'
Fix: Define the variable; for optional variables use default(); declare the required parameters in the role's meta/argument_specs.yml so errors surface early. From 2.19+, error messages include a variable origin hint that helps locate the file and line.
fatal: [node2]: FAILED! => {"changed": false, "module_stderr": "/bin/sh: 1: /usr/bin/python3: not found\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 127}
Layer:④ Module. Cause: There is no Python on the remote host, or ansible_python_interpreter points to a path that does not exist.
ansible node2 -m raw -a 'command -v python3 python3.12; ls -l /usr/bin/python3*'
Fix: Install Python with raw (apt-get install -y python3), or correct the interpreter path. See the interpreter discovery in Module 3.
[WARNING]: Ansible is being run in a world writable directory (/mnt/c/lab), ignoring it as an ansible.cfg source.
Layer: Configuration (affects all layers). Cause: A security mechanism that prevents other users from placing malicious configuration.
Fix: Move the project to a Linux filesystem, or chmod o-w directory; or explicitly set export ANSIBLE_CONFIG=$PWD/ansible.cfg (when you have confirmed the directory is trusted).
1. Verify only the SSH channel to node2 (without relying on remote Python or the temp directory), and output OpenSSH's debug information.
ansible node2 -m ansible.builtin.raw -a 'true' -vvvv
2. Keep the remote file from one ansible.builtin.stat call, and manually re-run it on node1.
ANSIBLE_KEEP_REMOTE_FILES=1 ANSIBLE_PIPELINING=False ansible node1 -m ansible.builtin.stat -a 'path=/etc/hosts' -vvv | grep 'PUT .*AnsiballZ' docker exec -u ansible node1 sh -c 'cd $(ls -dt ~/.ansible/tmp/ansible-tmp-* | head -1) && python3 AnsiballZ_stat.py explode && python3 AnsiballZ_stat.py execute'
A colleague says: “My playbook reports 'dict object' has no attribute 'db_host' in a template task. I have already SSHed to the server and checked the file permissions, and they are fine.” Point out where his troubleshooting direction went wrong, and give the correct steps.
This is a templating-layer error that occurs during control-node rendering; nothing runs on the remote host at all, so checking the server's file permissions is pointless. Correct steps: ① -vvv confirm the task before it has no SSH: EXEC; ② ansible-inventory --host H check the merged variables for this host and confirm the dict structure of db_host (it may be nested under app.db.host); ③ use debug: var=… to print the parent dict; ④ check whether a higher-precedence dict with the same name overrides the whole dict (by default hash_behaviour=replace, dicts are not merged); ⑤ after fixing, use default() for optional keys.
Verified teaching videos
Official documentation
- Debugging modules (KEEP_REMOTE_FILES, explode/execute)
- Ansible Configuration Settings (DEFAULT_DEBUG, DEFAULT_KEEP_REMOTE_FILES)
- ansible.builtin.ssh connection plugin
- Porting guide core 2.19 (templating engine changes)
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided, which can be passed to a video tool.
Scene: thousands of lines of -vvvv output scroll in the terminal; the camera pulls back to reveal a “wall of text.”
Narration: turning on the highest log level whenever there is an error is the most common low-efficiency way to troubleshoot.
Scene: five stacked colored blocks: inventory, templating, connection, privilege escalation, module; a task icon passes through them from top to bottom.
Narration: a task passes through five layers. Inventory determines hosts and variables; templating renders parameters on the control node; the connection plugin delivers the module; become escalates privileges; finally the remote Python runs and returns JSON.
Scene: the error text UNREACHABLE flies to the “connection” layer; undefined flies to the “templating” layer; MODULE FAILURE flies to the “module” layer.
Narration: the error text itself tells you which layer it belongs to. Sort by layer first, then verify with the cheapest checks: ansible-inventory, ping, and ping with b.
Scene: an AnsiballZ file appears in the remote directory; run explode to expand it into debug_dir.
Narration: for module-layer problems, keep the remote file with KEEP REMOTE FILES; after explode unpacks it, you can debug the module directly on the managed node.
Module 2 · Playbook debugger and debug tips
- Use the
debugger:keyword (always / never / on_failed / on_unreachable / on_skipped) orANSIBLE_ENABLE_TASK_DEBUGGER=Trueto enter the debugger. - Master the debugger commands:
p task/p task.args/p task_vars/p result._result,task.args[...] = …,task_vars[...] = …+u(update_task),r(redo),c,q. - Use
assertto turn implicit assumptions into explicit checks; use--list-tasks,--start-at-task,--step,--limit,--tagsto narrow the replay scope.
What: task debugger
The Playbook debugger is the interactive REPL built into ansible-playbook. When a task meets its entry condition (for example, it fails), execution pauses, and you can, in the same process, with the same variables and the same established connection, inspect the task object, module parameters, variables and return results, modify parameters, and re-run that task without running the whole playbook again.
debugger: Value | When to enter the debugger |
|---|---|
always | Always enter, regardless of result |
never | Never enter (can be used to override a global setting) |
on_failed | When the task fails |
on_unreachable | When the host is unreachable |
on_skipped | When the task is skipped (the debugger's when condition is useful) |
debugger Can be set on play, role, block or task; the more specific the level, the higher the priority (task > block > play/role). Enable globally: [defaults] enable_task_debugger = True or ANSIBLE_ENABLE_TASK_DEBUGGER=True, in which case any failed task enters the debugger (unless overridden by debugger: never ). There is also an older method strategy: debug (ANSIBLE_STRATEGY=debug), which the official docs say may be removed in a future version, so use the keyword for new projects.
Why: why it is needed
- A 40-minute playbook fails at minute 35; re-running after fixing one parameter is too costly.
- Some failures only occur in a specific state (registered variables produced by earlier tasks, a certain fact), and may not reproduce on rerun.
- The debugger lets you see all the fields of
result._resultdirectly, which is easier to explore interactively than-voutput.
How: debugger commands
| Command | Abbreviation | Purpose |
|---|---|---|
print task / p task | p | show the task name; p task.args module parameters; p task_vars all variables; p host current host; p result._result return result |
task.args['key'] = value | — | modify module parameters; a direct redo takes effect |
task_vars['key'] = value | — | modify variables; must first u (update_task) re-template the task, then redo |
update_task | u | rebuild the task with the modified task_vars |
redo | r | re-run this task |
continue | c | continue to the next task (the current failure result is kept) |
quit | q | exit the debugger and abort playbook |
Changes made in the debugger only apply to this run and are not written back to the YAML. Once fixed, be sure to sync the changes into the code. free strategy When the debugger is active, other queued tasks do not run; during redo, other hosts' queued tasks may run first.
Other “narrow-the-scope” tools
| Tool | Usage | Suitable for |
|---|---|---|
ansible.builtin.assert | that: list of boolean expressions + fail_msg/success_msg,quiet: true reduce output | write preconditions as code (variable scope, version, disk) |
ansible.builtin.debug | var: or msg:,verbosity: 2 shown only at -vv and above | diagnostic output left in the code long-term |
--list-tasks / --list-hosts / --list-tags | does not execute; only lists | the tasks that will actually run after include/when/tags are evaluated |
--syntax-check | only parses YAML and structure | first gate in CI |
--start-at-task "name" | start from the task with the given name (wildcards supported) | continue from the failure point after a fix |
--step | ask before each task (N)o/(y)es/(c)ontinue | cautiously advance production changes step by step |
--limit / --tags | narrow the host and task scope | reproduce on only one host |
When: how to choose
- Development stage:
ANSIBLE_ENABLE_TASK_DEBUGGER=Truerun locally. - CI / AWX: do not enable the debugger (there is no interactive terminal, so the job hangs until timeout). Use
assertand-vv. - Manual production changes:
--step+--check --diffrehearse first.
Compared with similar techniques
| Ansible debugger | Python pdb | Terraform | |
|---|---|---|---|
| pause point | task granularity | code-line granularity | non-interactive debugger (terraform console only evaluates expressions) |
| retry after changes | redo re-run the current task | continue after modifying variables | re-plan after modifying code |
| debug the module code itself | no → use explode from Module 1 or remote IDE debugging | yes | — |
u. ② “q equals continue”—q aborts the whole playbook; to continue, use c. ③ “--start-at-task automatically brings in variables registered by earlier tasks”—no; skipped tasks do not run, so their register variables and set_fact do not exist, so undefined errors may follow. ④ “debug module output always shows”—when you set verbosity: 2 , it only shows at -vv and above (displayed as skipping).State diagram: the debugger's position in the task lifecycle
Workflow: from failure to fixed code
Interaction: in-browser debugger terminal
The following simulates one real session: task configure app uses lineinfile to write /etc/myap.conf (one 'p' is missing); the file does not exist, so it fails and enters [node1] TASK: configure app (debug)>. Try the commands in the input box in turn (or click the shortcut buttons below): p result._result['msg'] → p task.args → task.args['path'] = '/etc/myapp.conf' → r → c. Another path: modify task_vars['app_port'] = 9000 and forget to u directly r, and see what happens.
[node1] TASK: configure app (debug)>Core commands and parameters
| Command / configuration | Purpose | Key parameters / notes |
|---|---|---|
ANSIBLE_ENABLE_TASK_DEBUGGER=True | Global: any failure enters the debugger | accepts only True/False |
debugger: on_failed | enable at play/block/task level | the most specific level takes precedence |
ansible-playbook --list-tasks | list the tasks that will run (with tags) | used with --tags/--skip-tags |
--start-at-task 'configure*' | start from a given task | skipped tasks do not register variables |
--step | confirm each task | y run / n skip / c no longer ask afterwards |
--syntax-check | syntax check | does not connect to hosts |
ansible.builtin.assert | assertions | that,fail_msg,success_msg,quiet |
- name: debugger demo
hosts: node1
gather_facts: false
become: true
debugger: on_failed # play level: any failure in this play enters the debugger
vars:
app_port: 8000
tasks:
- name: prepare
ansible.builtin.copy:
dest: /etc/myapp.conf
content: "# managed\n"
mode: "0644"
- name: validate inputs
ansible.builtin.assert:
that:
- app_port | int > 1024
- app_port | int < 65536
fail_msg: "app_port={{ app_port }} is not within 1025-65535"
success_msg: "app_port is valid"
quiet: true
- name: configure app
ansible.builtin.lineinfile:
path: /etc/myap.conf # intentional typo
regexp: '^port='
line: "port={{ app_port }}"
- name: show result
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.pipe', 'date +%T') }} done"
- name: verbose-only diagnostics
ansible.builtin.debug:
var: hostvars[inventory_hostname]['ansible_host']
verbosity: 2
ansible-playbook debug.yml --list-tasks ansible-playbook debug.yml
playbook: debug.yml
play #1 (node1): debugger demo TAGS: []
tasks:
prepare TAGS: []
validate inputs TAGS: []
configure app TAGS: []
show result TAGS: []
verbose-only diagnostics TAGS: []
TASK [configure app] ***********************************************************
fatal: [node1]: FAILED! => {"changed": false, "msg": "Destination /etc/myap.conf does not exist !", "rc": 257}
[node1] TASK: configure app (debug)> p task.args
{'line': 'port=8000', 'path': '/etc/myap.conf', 'regexp': '^port='}
[node1] TASK: configure app (debug)> task.args['path'] = '/etc/myapp.conf'
[node1] TASK: configure app (debug)> r
changed: [node1]
[node1] TASK: configure app (debug)> c
TASK [show result] *************************************************************
ok: [node1] => {"msg": "10:21:07 done"}
TASK [verbose-only diagnostics] ************************************************
skipping: [node1]
How to verify:docker exec node1 cat /etc/myapp.conf should contain port=8000. Common errors: leaving it in CI debugger: on_failed, the job will hang waiting for input; assert written as app_port > 1024 without adding | int—when the variable comes from the command line, -e it is a string, and 2.19+ gives a clearer error when comparing a string with an integer. Production use: write key preconditions as assert and place it as the first task in the role.
Changing variables requires update_task
[node1] TASK: configure app (debug)> task_vars['app_port'] = 9000 [node1] TASK: configure app (debug)> u [node1] TASK: configure app (debug)> p task.args['line'] 'port=9000' [node1] TASK: configure app (debug)> r
Starting from the middle, and stepping through
ansible-playbook site.yml --start-at-task 'root-only*' --limit node2 ansible-playbook site.yml --step --check --diff ansible-playbook site.yml --syntax-check
Perform task: TASK: connectivity (N)o/(y)es/(c)ontinue: y … Perform task: TASK: render config (template layer) (N)o/(y)es/(c)ontinue: n
Experiment 2: fix live in the debugger + assertions to prevent regression (about 7 minutes)
debug.yml and run it ansible-playbook debug.yml, and in the debugger run in order:
p task p result._result['msg'] p task.args task.args['path'] = '/etc/myapp.conf' r c
TASK: configure app
'Destination /etc/myap.conf does not exist !'
{'line': 'port=8000', 'path': '/etc/myap.conf', 'regexp': '^port='}
changed: [node1]debug.yml append a skipped task, and enable tracing only for it on_skipped:
- name: only on web hosts
ansible.builtin.debug:
msg: "web!"
when: "'web' in group_names and app_port | int == 80"
debugger: on_skipped
p task_vars['group_names'] p task_vars['app_port'] task_vars['app_port'] = 80 u r c
you will see which half of the condition is false; modify the variable and u then redo, and the task becomes ok.
ansible-playbook debug.yml -e app_port=80
TASK [validate inputs] *********************************************************
fatal: [node1]: FAILED! => {"assertion": "app_port | int > 1024", "changed": false, "evaluated_to": false, "msg": "app_port=80 is not within 1025-65535"}
[node1] TASK: validate inputs (debug)>
The play-level debugger: on_failed still applies (keywords take precedence over configuration); enter q to quit. To run in a non-interactive environment, you can temporarily change the keyword to debugger: never, or do not commit code with debugger in CI.
path to /etc/myapp.conf, remove the play-level debugger, and run ansible-playbook debug.yml --syntax-check && ansible-lint debug.yml before committing (ansible-lint was installed in Lesson 2).ansible node1 -b -m ansible.builtin.file -a 'path=/etc/myapp.conf state=absent'
Case 1: the database migration playbook fails at step 9
Problem: The 12-step PostgreSQL upgrade playbook fails at step 9 (community.postgresql.postgresql_query) because of an extension-name case error; the first 8 steps took 25 minutes and cannot easily be replayed. Approach: During the maintenance window, when running manually, enable debugger: on_failed for the whole play; after the failure, fix task.args['query'] and redo, to finish the remaining steps; afterwards commit the fix and add assert a check of the extension list. Limitations: The debugger is only suitable for runs attended by a person; do not enable it in AWX job templates.
Case 2: --start-at-task causes undefined
Problem: After a fix, an engineer used --start-at-task 'deploy app' to continue, and it reported 'release_dir' is undefined—this variable was set by an earlier, skipped task using set_fact . Approach: Change the key derived variable to vars/defaults an expression that can be computed inline, or tag the “compute variable” task with tags: [always]. Limitation:always Tags on --start-at-task do not work; the structure needs to be changed to a re-entrant one.
Case 3: production change using --step as a “manual gate”
Problem: The network team requires every change step to be visible and rejectable. Approach: Run ansible-playbook change.yml --limit canary --check --diff as a dry run in the change window, then --step for real; print a debug summary before key tasks. Limitation: At scale, use AWX approval nodes (Lesson 5),--step which is only suitable for a small number of hosts.
Common errors and fixes
After changing task_vars in the debugger and redoing, the result is still the old value
Cause: The task parameters were templated from the old variables before the debugger was entered.
Fix: After changing task_vars , first run u (update_task), use p task.args to confirm the new value, then r. For changes to task.args you don't need to u.
The CI job runs until it times out, and the last log line is "[host] TASK: xxx (debug)>"
Cause: A debugger: keyword was left in the code, or ANSIBLE_ENABLE_TASK_DEBUGGER is set in the environment, so it waits for input in a non-interactive environment.
grep -rn 'debugger:' --include='*.yml' . ; env | grep -i ANSIBLE_ENABLE_TASK_DEBUGGER; ansible-config dump --only-changed | grep -i debugger
Fix: Remove the keyword; forbid committing debugger: in a custom ansible-lint rule or in pre-commit.
ERROR! the playbook: site.yml could not be found / [WARNING]: No task named 'Deploy app' found
Cause:--start-at-task name does not match (case differences, or a task name inside an include that carries a role prefix role : task).
ansible-playbook site.yml --list-tasks | grep -i deploy
Fix: copy the name shown in --list-tasks ; use the wildcard --start-at-task 'myrole : deploy*'.
fatal: [node1]: FAILED! => {"msg": "The conditional check 'app_port > 1024' failed. The error was: '>' not supported between instances of 'str' and 'int'"}
Cause: The value from -e app_port=80 is a string.
Fix: Use app_port | int; or pass it as JSON -e '{"app_port": 80}'; in the role, use argument_specs to declare type: int for automatic validation and conversion.
The debug task shows "skipping: [node1]" and prints nothing
Cause: a verbosity filter has been set with verbosity: N, but the current -v level is not high enough.
Fix: Run with -vv (N=2), or remove the verbosity filter. This is the recommended way to keep diagnostic output permanently in the code without disturbing everyday output.
1. Without modifying any YAML, make any task that fails in site.yml enter the debugger, and run it only on node2.
ANSIBLE_ENABLE_TASK_DEBUGGER=True ansible-playbook site.yml --limit node2
2. In the debugger, change the current task's module parameter state to present and re-run it, then continue the playbook.
task.args['state'] = 'present' r c
A role runs on 30 hosts; only 2 hosts fail at “render nginx.conf” with the error 'dict object' has no attribute 'upstreams'. You have a 10-minute window. Describe your debugging order.
① --limit Focus only on these 2 hosts,--start-at-task 'nginx : render nginx.conf' (first use --list-tasks to confirm the name), and check whether the skipped task registered the required variable; ② set ANSIBLE_ENABLE_TASK_DEBUGGER=True, and after the failure p task_vars['nginx'] compare with a normal host (open another terminal ansible-inventory --host good_host); ③ most likely the host_vars of these 2 hosts override the whole nginx dictionary with replace-style logic, missing the upstreams key; ④ in the debugger, task_vars['nginx']['upstreams'] = [...] → u → r complete this change; ⑤ afterwards fix host_vars (override only the keys needed, or use combine), and add assert: that: nginx.upstreams is defined at the top of the role.
Verified teaching videos
No video verified via oEmbed that specifically explains the playbook debugger (the debugger keyword) was found; refer to the official docs and the storyboard below.
Official documentation
- Debugging tasks (playbook debugger)
- ansible.builtin.assert
- Executing playbooks for troubleshooting (--start-at-task / --step)
- ansible.builtin.debug strategy
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: the progress bar turns red at 90%, the “Rerun from start” button flashes, and the clock shows 40 minutes.
Narration: a long playbook fails in the last few steps, and rerunning from the start is very expensive.
Scene: a debug prompt appears in the terminal; type p result, then p task, then click args.
Narration: add debugger on_failed to the play; when a failure occurs, execution stops and you can inspect the result and the module parameters.
Scene: change the path in task.args, enter r, and the result turns green; a tip pops up beside it: remember to enter u first when changing task_vars.
Narration: after changing parameters, enter r to re-run the task; if you changed a variable, first use update task to re-template.
Scene: the YAML is corrected in the editor, and an assert task is added at the top.
Narration: changes made in the debugger are not written back to the file. Always change the code at the end, and use assert to prevent the same problem from recurring.
Module 3 · Deep dive into connection and privilege issues
- Explain one by one the command generated by the ssh connection plugin:
-C,ControlMaster/ControlPersist/ControlPath,ConnectTimeout,PreferredAuthenticationsetc., and the difference betweenssh_args,ssh_common_args,ssh_extra_args. - Handle host key issues (first connection, key changes), and understand the security implications of
host_key_checking. - Diagnose become: the sudo password (
-K/ansible_become_password),requiretty, temp-file permissions when becoming a non-privileged user (setfacl / chown / common_remote_group / world_readable_temp / pipelining). - Understand Python interpreter discovery (
interpreter_python=auto) and its warnings and failures.
What: what the ssh connection plugin does
ansible.builtin.ssh The plugin does not implement the SSH protocol itself; it calls the system's OpenSSH client, translating inventory variables into -o parameters. So ~/.ssh/config,ssh-agent,known_hosts, ProxyJump and other OpenSSH features can be reused directly (another connection plugin ansible.netcommon.libssh is used for network devices and is not discussed here). Key defaults verified 2026-11:
| Option | Default | ini / env var / inventory variable |
|---|---|---|
| ssh_args | -C -o ControlMaster=auto -o ControlPersist=60s | [ssh_connection] ssh_args / ANSIBLE_SSH_ARGS / ansible_ssh_args |
| ssh_common_args / ssh_extra_args | empty | ansible_ssh_common_args (shared by ssh/scp/sftp, such as ProxyJump),ansible_ssh_extra_args (ssh only) |
| control_path_dir | ~/.ansible/cp | ANSIBLE_SSH_CONTROL_PATH_DIR |
| control_path | if unset, Ansible generates a hashed file name | ANSIBLE_SSH_CONTROL_PATH |
| timeout | 10 seconds (→ ConnectTimeout) | ANSIBLE_TIMEOUT / ansible_ssh_timeout |
| reconnection_retries | 0 | [ssh_connection] retries / ANSIBLE_SSH_RETRIES |
| host_key_checking | True | ANSIBLE_HOST_KEY_CHECKING |
| transfer_method | smart (try sftp first, fall back to scp on failure) | ANSIBLE_SSH_TRANSFER_METHOD |
| pipelining | False | ANSIBLE_PIPELINING / ansible_pipelining |
ControlPersist: when a host is first connected, OpenSSH establishes a background "master" connection and places a Unix socket at ControlPath ; subsequent ssh/sftp calls to the same host:port:user reuse the authenticated TCP connection through this socket, avoiding TCP setup + key exchange + authentication (typically 100–500 ms, more across continents). The master connection exits after 60 seconds idle. Note that Unix socket paths have a length limit (about 104–108 bytes); a custom control_path that is too long will raise an error, which is why Ansible defaults to short hash names.
Why: why connection and privilege issues are so common
- They depend on the state of the managed node (sshd configuration, sudoers, home permissions, Python), which the playbook does not control; these are often silently changed by images, hardening baselines, or reinstalls.
- Error messages are often just one raw line from OpenSSH or sudo, so you must understand the underlying mechanism to read them.
How (1): become
The become plugin wraps the module execution command. Core built-ins are sudo,su,runas (Windows); others (doas,pbrun,dzdo,machinectl,ksu , etc.) are in community.general . Common variables: ansible_become,ansible_become_method,ansible_become_user (default root),ansible_become_password,ansible_become_flags,ansible_become_exe.
- sudo password: when no password is supplied, Ansible adds
-nto sudo, so if sudo requires a password it fails immediately →Missing sudo password; use-K(--ask-become-pass, the same password for all hosts), or a vault-encryptedansible_become_password. - requiretty: in sudoers,
Defaults requirettyrequires a terminal. Without pipelining, the ssh plugin uses-ttto allocate a pseudo-terminal, which is usually fine; with pipelining enabled, the module is passed via stdin, so no tty can be allocated, and sudo reportssorry, you must have a tty to run sudo. So the official docs require disabling requiretty in sudoers before using pipelining (modern distributions no longer enable it by default). - become to a non-privileged user (for example
become_user: appsvc): the connecting useransiblewrites the module file, andappsvcmust be able to read it. Ansible tries in order: ① setfacl (requires theaclpackage and a filesystem that supports POSIX ACLs) → ② chown (most systems do not allow ordinary users to chown) → ③ macOS's chmod +a → ④ansible_common_remote_group(chgrp to a group shared by both) → ⑤world_readable_temp(file is globally readable, with a risk of leaking parameters). If all fail, it reportsFailed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user. pipelining (no file written) can bypass this whole logic, but itcopy/template/fetchdoes not apply to actions that need to transfer files, or to non-Python modules.
How (2): Python interpreter discovery
interpreter_python Default auto: before the first module run on a host, Ansible uses an extra SSH call to run a shell script that reads /etc/os-release and probes a list of candidate paths in order (newer versions first), then combines this with a built-in "distribution → preferred interpreter" table to decide which to use. The result is cached as ansible_facts.discovered_interpreter_python. auto prints a warning when a non-preferred path is used; auto_silent does not print; auto_legacy has been removed or deprecated in newer versions (check your version's configuration docs). You can also set ansible_python_interpreter=/usr/bin/python3.12 on a single host to skip discovery.
2.21 requires managed-node Python 3.9–3.14. Older systems (CentOS 7's Python 2.7/3.6) cannot be managed by 2.21; use an older ansible-core or upgrade the system. This is a common version problem at the module layer.
When: recommended for production
- Use
~/.ssh/configto manage the jump host (ProxyJump), and only writeansible_ssh_common_args='-o ProxyJump=bastion'in Ansible, or rely fully on ssh config. - Extend
ControlPersist(e.g.10m) to cover the gap between two visits to the same host in a long playbook. - Keep
host_key_checking=True; use thessh-keyscan/known_hostsmodule or an SSH CA to manage host keys. - Use vault or external secrets for sudo passwords in CI, not plaintext; if passwordless is possible, configure a restricted NOPASSWD rule for the automation account.
Comparison with similar techniques
| ssh plugin | paramiko_ssh | SSM (amazon.aws.aws_ssm) | |
|---|---|---|---|
| Implementation | calls the OpenSSH binary | pure Python library | AWS Session Manager, no need to open port 22 |
| ControlPersist | Supports | Not supported (in-process reuse) | Not applicable |
| Applicable | Default first choice | Legacy environments, control nodes without OpenSSH | Lesson 4 Module 4 |
host_key_checking=False just turns off an annoying prompt”—it disables man-in-the-middle detection and silently adds unknown keys to known_hosts. ② “setting ansible_become_password automatically escalates privileges”—you still need become: true; -K supplying only a password does not enable become. ③ “Permission denied (publickey) must mean the key is wrong”—it may also be caused by home or .ssh permissions that are too loose (sshd StrictModes rejects them), a wrong username, or too many keys in ssh-agent triggering Too many authentication failures. ④ “ControlPersist is an Ansible feature”—it is an OpenSSH feature, and a leftover master can be ssh -O check/exit managed.Sequence diagram: how many SSH round-trips one non-pipelining become task makes
Decision diagram: order of permission handling for become to a non-privileged user
Interaction: SSH command breakdown + ControlPersist simulation
The top half shows the real -vvv command that appears in SSH: EXEC ; click any parameter to see which Ansible option it comes from, what it does, and the typical error when it goes wrong. The bottom half simulates ControlPersist: run several tasks in a row and observe when a full handshake is needed, when the master is reused, and what happens after more than 60 seconds of idle time.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
ssh -O check -o ControlPath=~/.ansible/cp/HASH 127.0.0.1 | Check whether the master is alive | -O exit Close a leftover master |
ssh-keygen -R '[127.0.0.1]:2222' | Delete an old host key | A non-22 port needs [host]:port format |
ssh-keyscan -p 2222 127.0.0.1 | Get the host public key | In production, verify the fingerprint against a trusted source |
ansible H -m ping -b -K | Enter sudo password interactively | --become-password-file Read from a file |
ansible H -m setup -a 'filter=ansible_python*' | View Python information | discovered_interpreter_python in ansible_facts in |
ansible H -m raw -a '…' | does not depend on Python or the temp directory | The preferred command for fixing Python and checking sudoers |
View and manage ControlPersist
ansible lab -m ping -o >/dev/null ls -la ~/.ansible/cp/ ps -ef | grep '[s]sh: .*\[mux\]'
srw------- 1 azureuser azureuser 0 Nov 15 10:31 3f1c0a2b9d srw------- 1 azureuser azureuser 0 Nov 15 10:31 8e2d71c4a0 srw------- 1 azureuser azureuser 0 Nov 15 10:31 c0b9a1e352 azureuser 51022 1 0 10:31 ? 00:00:00 ssh: /home/azureuser/.ansible/cp/3f1c0a2b9d [mux]
# Close all leftover masters (for example, to force a new handshake after changing the ssh config) for s in ~/.ansible/cp/*; do ssh -O exit -o ControlPath="$s" dummy 2>/dev/null; done
Host key
./faults.sh 2 ansible node2 -m ping
node2 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n…\r\nHost key for [127.0.0.1]:2222 has changed and you have requested strict checking.\r\nHost key verification failed.",
"unreachable": true
}
ssh-keygen -R '[127.0.0.1]:2222' ssh-keyscan -p 2222 127.0.0.1 2>/dev/null | tee -a ~/.ssh/known_hosts | ssh-keygen -lf - ansible node2 -m ping -o
Production use: After rebuilding a host, verify the fingerprint through a trusted channel (cloud platform serial console output, cloud-init logs, configuration management database) rather than blindly trusting keyscan results. You can also use ansible.builtin.known_hosts module to manage them centrally.
sudo password
./faults.sh 3 ansible node2 -m ping -b ansible node2 -m ping -b -K # enter Passw0rd!
node2 | FAILED! => {
"msg": "Missing sudo password"
}
BECOME password:
node2 | SUCCESS => {
"changed": false,
"ping": "pong"
}
Non-interactive scenarios: ansible-vault encrypt_string 'Passw0rd!' --name ansible_become_password >> host_vars/node2/vault.yml, at runtime --ask-vault-pass or --vault-password-file.
requiretty and pipelining
./faults.sh reset && ./faults.sh 5 ansible node2 -m ping -b
node2 | FAILED! => {
"changed": false,
"module_stderr": "sudo: sorry, you must have a tty to run sudo\n",
"module_stdout": "",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
ANSIBLE_PIPELINING=False ansible node2 -m ping -b -o # turning pipelining off restores it immediately → confirms requiretty ansible node2 -m raw -a "sudo rm -f /etc/sudoers.d/00-tty" -b -e ansible_pipelining=false ansible node2 -m ping -b -o
become to a non-privileged user
./faults.sh reset && ./faults.sh 6 ansible node2 -m ansible.builtin.command -a 'id -un' -b --become-user appsvc
node2 | 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'\nTry 'chmod --help' for more information.\n}). For information on working around this, see https://docs.ansible.com/ansible-core/2.21/playbook_guide/playbooks_privilege_escalation.html#risks-of-becoming-an-unprivileged-user"
}
The error shows the output of the last attempt (macOS's chmod +a syntax) failing on Linux. This is the most common misleading appearance of this error; the real cause is that setfacl does not exist. The exact err content may vary slightly between versions.
# Option A (recommended): install acl ansible node2 -b -m ansible.builtin.apt -a 'name=acl state=present' # Option B: pipelining (the command module is a Python module, so it works) ansible node2 -m command -a 'id -un' -b --become-user appsvc -e ansible_pipelining=true # Option C: shared group (ansible and appsvc are both in appgrp) # ansible_common_remote_group=appgrp
Python interpreter
ansible lab -m ansible.builtin.setup -a 'filter=ansible_python_version' -o ansible node1 -m ping -e ansible_python_interpreter=/usr/bin/python3.12 -o ANSIBLE_PYTHON_INTERPRETER=auto ansible node1 -m ping -vvv 2>&1 | grep -iE 'interpreter|os-release' | head -3
Experiment 3: reproduce and fix 4 connection/privilege-escalation faults (about 8 minutes)
Each step follows: inject → observe the raw error → use the minimal command to determine the layer → fix → ./faults.sh reset.
./faults.sh 2; ansible node2 -m ping -o ansible node2 -m raw -a true -vvvv 2>&1 | grep -E 'Server host key|Host key verification' ssh-keygen -R '[127.0.0.1]:2222'; ssh-keyscan -p 2222 127.0.0.1 >> ~/.ssh/known_hosts 2>/dev/null ansible node2 -m ping -o; ./faults.sh reset
./faults.sh 3; ansible node2 -m ping -b -o ansible node2 -m ping -o # without privilege escalation it works normally → privilege layer ansible node2 -m ping -b -K -o # Passw0rd! ./faults.sh reset
node2 | FAILED! => {"msg": "Missing sudo password"}
node2 | SUCCESS => {"changed": false,"ping": "pong"}
BECOME password:
node2 | SUCCESS => {"changed": false,"ping": "pong"}./faults.sh 5; grep pipelining ansible.cfg ansible node2 -m ping -b -o ANSIBLE_PIPELINING=False ansible node2 -m ping -b -o ./faults.sh reset
Controlled experiments are the most important technique in this module: change only one variable (pipelining); if the fault appears or disappears with it, you can determine the root cause.
./faults.sh 6 ansible-playbook site.yml --limit node2 --start-at-task 'run as unprivileged*' ansible node2 -m raw -a 'command -v setfacl || echo NO_SETFACL' ansible node2 -b -m apt -a 'name=acl state=present' ansible-playbook site.yml --limit node2 --start-at-task 'run as unprivileged*' ./faults.sh reset
fatal: [node2]: FAILED! => {"msg": "Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user …"}
node2 | CHANGED | rc=0 >>
NO_SETFACL
…
ok: [node2]
The container must be able to reach the Ubuntu package repositories to reinstall acl; when offline, verify with option B (pipelining).
./faults.sh 4; ansible node2 -m ping ansible node2 -m raw -a 'ls -l /usr/bin/python3*' ansible node2 -m raw -a 'mv /usr/bin/python3.12.off /usr/bin/python3.12' -b ansible node2 -m ping -o; ./faults.sh reset
Case 1: 800 hosts behind a jump host, Gathering Facts is extremely slow
Problem: All connections go through the bastion,forks=50 and the bastion's sshd starts MaxStartups dropping connections, so some hosts randomly become UNREACHABLE. Approach: In ~/.ssh/config enable ControlMaster on the bastion itself (multiple ProxyJump connections reuse the connection to the bastion); on the bastion, increase MaxStartups 100:30:200 and MaxSessions; in Ansible, set [ssh_connection] retries = 3. Configuration:Host bastion section ControlMaster auto,ControlPersist 10m; Host 10.* section ProxyJump bastion. Limitations: retries will mask the real instability, so the bastion still needs monitoring.
Case 2: after the hardening baseline enabled requiretty, all become tasks failed
Problem: The security team pushed a CIS baseline; sudoers gained Defaults use_pty and an old template brought in requiretty, while Ansible already had pipelining enabled. Approach: After confirming with a controlled experiment (turning pipelining off restores it immediately), negotiate with the security team: for the automation account, Defaults:ansible !requiretty. Limitations:use_pty and requiretty are different options; the former usually does not affect Ansible.
Case 3: PostgreSQL tasks running as become_user: postgres fail
Problem: The minimal image does not have the acl package, so all community.postgresql tasks report “Failed to set permissions on the temporary files”. Approach: In the first step of the role, use become: true (root) to install acl, and add it to the base image. Limitations: Do not enable world_readable_temp for this: the module parameters may contain database passwords.
Common errors and fixes
Failed to connect to the host via ssh: ansible@127.0.0.1: Permission denied (publickey,password).
Cause: wrong user, wrong private-key path or overly permissive key permissions, wrong authorized_keys permissions or owner (sshd StrictModes), too many keys in ssh-agent.
ansible node2 -m raw -a true -vvvv 2>&1 | grep -E "Offering|Authentications that can continue|Trying private key|no such identity" docker exec node2 sh -c 'ls -ld /home/ansible /home/ansible/.ssh; ls -l /home/ansible/.ssh'
Fix: correct ansible_user / ansible_ssh_private_key_file; chmod 700 ~/.ssh; chmod 600 authorized_keys; when the agent has too many keys, add -o IdentitiesOnly=yes.
Failed to connect to the host via ssh: Control socket connect(/home/u/.ansible/cp/…): Connection refused / mux_client_request_session: read from master failed
Cause: the master process is dead but its socket file remains, or the remote sshd's MaxSessions has been exhausted.
ls -la ~/.ansible/cp; rm -f ~/.ansible/cp/*
Fix: clean up the leftover socket; increase the remote MaxSessions; on an unstable network, set retries.
unix_listener: path "/home/very/long/path/.ansible/cp/ansible-ssh-host-22-user.XXXXXXXX" too long for Unix domain socket
Cause: a custom control_path is too long (the Unix socket path limit is about 104–108 bytes).
Fix: use the default hashed naming (do not set control_path), or change control_path_dir to a short path such as /tmp/.acp.
fatal: [node2]: FAILED! => {"msg": "Timeout (12s) waiting for privilege escalation prompt: "}
Cause: sudo printed a prompt Ansible does not recognize (a custom lecture, an extra PAM module prompt, a localized su prompt), or remote reverse DNS lookups make sudo very slow.
ansible node2 -m raw -a 'time sudo -n true' -vvv
Fix: sudoers Defaults lecture=never; fix local hostname resolution in /etc/hosts ; increase timeout.
[WARNING]: Platform linux on host node1 is using the discovered Python interpreter at /usr/bin/python3.12, but future installation of another Python interpreter could change the meaning of that path.
Cause:interpreter_python=auto When discovery finds a path that is not the preferred one in that distribution's mapping table. This is not an error.
Fix: after confirming the path is correct, use auto_silent to suppress the warning, or set an explicit ansible_python_interpreter for that group.
1. After node2 is rebuilt its host key changes; correctly update known_hosts (port 2222) and verify.
ssh-keygen -R '[127.0.0.1]:2222' ssh-keyscan -p 2222 127.0.0.1 2>/dev/null >> ~/.ssh/known_hosts ansible node2 -m ping -o
2. Use one command to prove whether a become failure is caused by pipelining.
ANSIBLE_PIPELINING=False ansible node2 -m ping -b -o # compare with the result of ANSIBLE_PIPELINING=True
A newly brought-online batch of RHEL hosts: ansible -m ping is fine,-b is fine, but all become_user: oracle tasks fail, reporting a temporary-files permissions problem. The security team forbids world-readable temp files. Give 2 compliant options and their trade-offs.
Option 1: in the baseline image or the first task (as root), install the acl package, ensuring the filesystem where the temp directory lives supports POSIX ACLs. This is the most universal option and applies to all modules. Option 2: enable pipelining for these hosts (and confirm sudoers does not enable requiretty). No temp files are written and it is even faster, but copy/template and other actions that transfer files still need temp files, so the problem can still occur. Option 3 (supplementary): put the ansible and oracle users into the same group and set ansible_common_remote_group, noting that Ansible does not verify whether become_user is actually in that group.
Verified teaching videos
Official documentation
- ansible.builtin.ssh connection
- Understanding privilege escalation: become
- Interpreter Discovery
- Connection methods and details
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: a very long ssh command, with parameters highlighted in turn: ControlMaster, ControlPersist, ControlPath, ConnectTimeout.
Narration: Ansible does not implement SSH itself; it calls OpenSSH and translates inventory variables into these parameters.
Scene: a handshake animation plays on the first connection; later tasks pass quickly through an existing pipe; after 60 seconds the pipe disappears.
Narration: ControlPersist lets later commands reuse the authenticated connection, which by default closes after sixty seconds of idleness.
Scene: a sudo gatekeeper blocks a task, showing Missing sudo password and must have a tty.
Narration: the three most common privilege-escalation problems are a missing password, a conflict between requiretty and pipelining, and temp files that cannot be read after switching to a non-privileged user.
Scene: the fallback chain setfacl, chown and the shared group light up in turn; finally the acl package is installed and the task turns green.
Narration: when switching to a non-privileged user, the simplest and most reliable fix is installing the acl package.
Module 4 · Performance: forks, pipelining, fact caching
- Understand the forks concurrency model (the number of control-node worker processes), and estimate “number of hosts / forks × single-task time”.
- Explain how pipelining reduces a task's SSH round-trips from 5–6 to 1, and its prerequisites (requiretty) and unsuitable scenarios.
- Configure fact caching (
jsonfile/community.general.redis) andgathering = smart, and usegather_subset/gather_facts: falseto reduce the amount collected. - Use
ansible.posix.profile_tasks,profile_roles,timercallbacks to output comparable timing data.
What: what makes up Ansible's run time
Rough model: Total time ≈ Σfor each task ⌈hosts / forks⌉ × single-host task time (linear strategy, with a synchronization barrier between tasks). Single-host task time ≈ number of SSH round-trips × RTT + file transfer + remote Python startup and module execution. This gives four levers:
| Lever | Setting | What it reduces | Typical gain | Cost / prerequisite |
|---|---|---|---|---|
| forks | [defaults] forks = 30 / -f 30 (default 5) | number of batches ⌈N/forks⌉ | multiplies when there are many hosts | control-node CPU/memory (each worker is a Python process); concurrency on remote / jump-host sshd |
| pipelining | [ssh_connection] pipelining = True | each task's SSH round-trips and file writes | 2–5× in high-RTT environments | sudoers must not require requiretty; copy/template and the like still need to transfer files |
| facts | gather_facts: false,gather_subset,gathering = smart + caching | execution of the setup module (often the slowest single task) | saves 1–10 seconds per host | cache expiry and consistency |
| strategy/async | strategy: free,async | fast hosts wait for slow hosts | noticeable when host speeds differ widely | see Module 5 |
How (1): forks
The ansible-playbook main process forks one worker process per “host × task”, with at most forks concurrent workers. A worker exits after connecting, running and returning its result. Bigger is not always better: each worker takes tens of MB of memory, and a 4-vCPU control node usually hits its CPU limit at around 50–100 forks (depending on modules and fact sizes), so measure it. In addition,serial limits the number of hosts per batch,throttle limits the concurrency of a single task, so either can make a higher forks setting ineffective (Module 5).
How (2): pipelining
Without pipelining (Module 3 Figure 3-1): determine home → create temp directory → sftp upload AnsiballZ → chmod → execute → delete, 5–6 round-trips in total. When enabled, Ansible runs one ssh … '/bin/sh -c '"'"'sudo … /usr/bin/python3 && sleep 0'"'"'' command and writes the AnsiballZ content directly to the stdin of this SSH session; the remote Python reads from stdin and executes, and the result returns via stdout—1 round-trip, nothing touches disk.
- Prerequisite: sudoers must not enable
requiretty(Module 3). - Not applicable: actions that need file transfer (
copy,template, the file-transfer part offetch) and non-Python modules; they automatically fall back to the normal method. - Side effects: KEEP_REMOTE_FILES has no file to keep (Module 1); it avoids the non-privileged become temp-file problem (Module 3).
How (3): facts
gathering([defaults], defaultimplicit):implicitevery play gathers them (unlessgather_facts: false);explicitdoes not gather by default;smartonly gathers for hosts that are not in the cache.fact_caching(defaultmemory, valid only within the current run):jsonfile(built into core,fact_caching_connectionis a directory),community.general.redis(connection string such aslocalhost:6379:0, requires the Pythonredislibrary),community.general.yaml/memcached/mongodbetc.fact_caching_timeoutThe default is 86400 seconds.gather_subset(play keyword or setup module parameter): e.g.['!all', 'min'],['!hardware', 'network'].hardwareThe subset option walks mount points and devices, often the slowest part.gather_timeoutLimit the time of a single fact collector.- When you only need a few values, you can turn facts off completely and use
ansible.builtin.setup: filter=…or a direct command to get them.
How (4): measurement
ansible.posix.profile_tasks Print a timestamp and the previous task's duration at the start of each task; at the end, list the slowest tasks sorted by duration; profile_roles summarize per role; timer print the total duration at the end. Enable with callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer (old name callback_whitelist has been removed). Another ansible.posix.cgroup_perf_recap can record each task's CPU/memory use on the control node (requires cgroup configuration).
When: tuning order
- first add
profile_tasks+timerto get a baseline,change only one variable at a time. - Turn off unneeded facts / narrow the subset (zero risk, big gain).
- Enable pipelining (confirm requiretty first).
- Raise forks according to control-node resources.
- Then consider the free strategy, async, splitting the playbook, and “fewer tasks, more parameters” (e.g. replacing a loop install with a single call that passes a list to
apt).
Comparison with similar techniques
| Ansible | Terraform | Salt / Puppet (agent mode) | |
|---|---|---|---|
| Concurrency | forks (processes) | -parallelism=10 (concurrency as shown in the figure) | agents run autonomously; the master handles distribution |
| State / fact caching | fact cache (optional) | state files (required) | grains / facts reported by the agent |
| Transfer cost | SSH per task (pipelining reduces it to 1) | cloud API calls | long-lived message bus |
MaxStartups. ② “pipelining is off by default for security reasons”—it is off by default because it is incompatible with requiretty, not because of a security problem. ③ “Once the fact cache is enabled, facts are never gathered again”—you still need gathering = smart (or manual control); otherwise the implicit mode still gathers facts for every play. ④ “profile_tasks is built into core”—it lives in the ansible.posix collection; when only ansible-core is installed, it must be installed separately.Comparison diagram: the same task, before and after enabling pipelining
Timeline: how forks determine batches
Core animation: pipelining round-trip comparison + forks timeline
Adjust RTT (network round-trip time between the control node and the managed node), the number of hosts and forks, then click “Play”. The top half plays one task's SSH round-trips one by one (left: pipelining off, right: on); the bottom half runs in batches by forks and totals the time. The log shows the real output lines that correspond to -vvv the lines below.
Core commands and configuration
| Command / configuration | Purpose | Notes |
|---|---|---|
callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer | Timing statistics | ANSIBLE_CALLBACKS_ENABLED |
forks = 30 / -f 30 | Concurrent workers | default 5 |
pipelining = True | execute the module in a single round-trip | [ssh_connection],[connection] or [defaults] are both fine |
gathering = smart | no collection if the cache hits | default implicit |
fact_caching = jsonfile + fact_caching_connection | cross-run fact caching | timeout default 86400 s |
gather_subset: ['!all','min'] | minimal facts | play keyword or setup parameter |
ansible-playbook --flush-cache | clear the fact cache for hosts in the inventory | use when the cache holds dirty data |
- name: perf baseline
hosts: scale
# gather_facts defaults to true (full facts)
tasks:
- name: show distro
ansible.builtin.debug:
msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"
- name: ensure dirs
ansible.builtin.file:
path: "/tmp/perf/{{ inventory_hostname }}/{{ item }}"
state: directory
mode: "0755"
loop: [conf, logs, run]
- name: write config
ansible.builtin.copy:
dest: "/tmp/perf/{{ inventory_hostname }}/conf/app.ini"
content: "host={{ inventory_hostname }}\n"
mode: "0644"
- name: check uptime
ansible.builtin.command: cat /proc/uptime
changed_when: false
- name: stat config
ansible.builtin.stat:
path: "/tmp/perf/{{ inventory_hostname }}/conf/app.ini"
export ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer ansible-playbook perf.yml -i inventory/scale.ini | tail -14
PLAY RECAP ********************************************************************* h01 : ok=6 changed=2 … … Saturday 15 November 2026 10:52:41 +0000 (0:00:03.912) 0:01:02.417 ***** =============================================================================== Gathering Facts ------------------------------------------------------- 21.83s ensure dirs ----------------------------------------------------------- 17.40s write config ---------------------------------------------------------- 9.12s stat config ----------------------------------------------------------- 6.01s check uptime ---------------------------------------------------------- 5.88s show distro ----------------------------------------------------------- 0.21s Playbook run took 0 days, 0 hours, 1 minutes, 2 seconds
How to verify: change only one variable per round, and record the timer total duration and the Gathering Facts time. Common mistakes: forgetting that ControlPersist is already established after the second round (within 60 seconds), which overstates the “optimization”; between rounds, run rm -f ~/.ansible/cp/* or wait 60 seconds to keep the results comparable.
Optimize item by item
# clean up the master and the previous run's files before each round
reset(){ rm -f ~/.ansible/cp/*; ansible scale -i inventory/scale.ini -m file -a 'path=/tmp/perf state=absent' -o >/dev/null; }
reset; ANSIBLE_FORKS=30 ansible-playbook perf.yml -i inventory/scale.ini | tail -1
reset; ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ansible-playbook perf.yml -i inventory/scale.ini | tail -1
[defaults] forks = 30 gathering = smart fact_caching = jsonfile fact_caching_connection = ./.facts_cache fact_caching_timeout = 7200 callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer [ssh_connection] pipelining = True ssh_args = -C -o ControlMaster=auto -o ControlPersist=10m
- name: perf tuned hosts: scale gather_facts: true gather_subset: ['!all', 'min'] # only a minimal set such as the distribution tasks: …
ls .facts_cache | head -3; python3 -c "import json;d=json.load(open('.facts_cache/h01'));print(len(d), d['ansible_distribution'])"
h01 h02 h03 38 Ubuntu
Redis cache (shared by multiple control nodes / AWX)
docker run -d --name facts-redis -p 6379:6379 redis:7-alpine pipx inject ansible redis # inject the Python redis library into the ansible installed by pipx ANSIBLE_CACHE_PLUGIN=community.general.redis \ ANSIBLE_CACHE_PLUGIN_CONNECTION=localhost:6379:0 \ ANSIBLE_GATHERING=smart ansible-playbook perf.yml -i inventory/scale.ini | tail -1 docker exec facts-redis redis-cli --scan --pattern 'ansible_facts*' | head -3
The Redis key prefix defaults to ansible_facts (can be changed with fact_caching_prefix ). For version details, see the community.general.redis documentation; in production, Redis should enable authentication and TLS (see the docs for the connection string format).
Experiment 4: 5 rounds of tuning for the same playbook (about 9 minutes) — the source of the performance report data
#!/usr/bin/env bash
# Usage: ./bench.sh name [extra environment variables...]
name=$1; shift
rm -f ~/.ansible/cp/*
ansible scale -i inventory/scale.ini -m ansible.builtin.file -a 'path=/tmp/perf state=absent' -o >/dev/null
start=$(date +%s.%N)
env "$@" ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks \
ansible-playbook perf.yml -i inventory/scale.ini > "bench-$name.log" 2>&1
end=$(date +%s.%N)
gf=$(grep -m1 '^Gathering Facts' "bench-$name.log" | grep -oE '[0-9.]+s$')
printf "%-14s total=%6.1fs facts=%s\n" "$name" "$(awk "BEGIN{print $end - $start}")" "${gf:-0s}" | tee -a bench.txt
chmod +x bench.sh; : > bench.txt; rm -rf .facts_cache
gather_subset to the play, or control it with environment variables):
./bench.sh R0-baseline ANSIBLE_FORKS=5 ANSIBLE_PIPELINING=False ./bench.sh R1-forks30 ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=False ./bench.sh R2-pipeline ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ./bench.sh R3-cache ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ANSIBLE_GATHERING=smart ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=./.facts_cache ./bench.sh R4-cachehit ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ANSIBLE_GATHERING=smart ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=./.facts_cache cat bench.txt
R0-baseline total= 62.4s facts=21.83s R1-forks30 total= 27.9s facts=8.10s R2-pipeline total= 16.3s facts=5.02s R3-cache total= 16.0s facts=4.96s R4-cachehit total= 9.4s facts=0s
R3 writes the cache for the first time, so it is not faster; R4 hits the cache,Gathering Facts no longer appears in the list (skipped in smart mode when everything hits). The local container RTT is close to 0, so pipelining gains less than over cross-region networks; in an Azure cross-region environment (RTT 50–80 ms), the R2 improvement will be more noticeable.
for p in False True; do echo "pipelining=$p: $(ANSIBLE_PIPELINING=$p ansible h01 -i inventory/scale.ini -m ping -b -vvv 2>&1 | grep -c 'SSH: EXEC') SSH EXEC lines"; done
pipelining=False: 5 SSH EXEC lines pipelining=True: 2 SSH EXEC lines
With it enabled, the remaining 2 lines are usually the first-time interpreter discovery (or home probing) plus the module execution itself. The sftp PUT lines disappear completely.
for s in min hardware network virtual; do echo -n "$s: "; TIMEFORMAT='%Rs'; time ansible h01 -i inventory/scale.ini -m setup -a "gather_subset=!all,$s" -o >/dev/null done
ansible scale -i inventory/scale.ini -m file -a 'path=/tmp/perf state=absent' -o >/dev/null rm -rf .facts_cache; docker rm -f facts-redis 2>/dev/null; true
Keep bench.txt, which the comprehensive lab's performance report will use.
Case 1: monthly patching of 2000 hosts reduced from 4 hours to 50 minutes
Problem: Default forks=5, every play gathers full facts, and the playbook has 6 plays. Approach: profile_tasks showed Gathering Facts took 38%. Changed the first play to gather ['!all','min','pkg_mgr'], and later plays gather_facts: false; enabled the jsonfile cache + smart; pipelining; raised forks to 100 (16-vCPU control node). Limitations: The patching play itself is a rolling serial: 10% update, so forks only take effect within a batch.
Case 2: after enabling pipelining in AWX, some jobs failed
Problem: After enabling pipelining in the AWX global settings, a batch of old RHEL hosts all reported sorry, you must have a tty to run sudo. Approach: First set ansible_pipelining: false on that inventory group as a stopgap, then push the sudoers change (Defaults:awx !requiretty), and remove the group variable after verification. Limitations: Have a contingency for the fallback: any global performance switch should first be verified on a canary group.
Case 3: the fact cache makes a new disk "invisible"
Problem: After expanding a disk, the playbook still thought there was only one disk—the jsonfile cache's ansible_devices expiry is 24 hours. Approach: In the play that depends on hardware facts, explicitly ansible.builtin.setup: gather_subset=hardware refresh; after ops changes, run --flush-cache. Limitations: Caching suits stable facts (distribution, architecture); volatile facts (disks, IP, mounts) need on-demand refresh.
Common errors and fixes
[WARNING]: Skipping callback plugin 'profile_tasks', unable to load / Invalid callback for stdout specified
Cause: is not installed ansible.posix, or a short name was used while the collection is not in the search path.
ansible-galaxy collection list | grep ansible.posix ansible-doc -t callback -l | grep -E 'profile|timer'
Fix:ansible-galaxy collection install ansible.posix; use the full FQCN ansible.posix.profile_tasks; change callback_whitelist to callbacks_enabled.
ERROR! Unexpected Exception, this is probably a bug: [Errno 24] Too many open files / BlockingIOError: Resource temporarily unavailable
Cause: forks is too high and exceeds the control node's ulimit -n or process limits.
ulimit -n; ulimit -u; nproc; free -m
Fix: lower forks or raise ulimit (/etc/security/limits.conf, the systemd unit's LimitNOFILE); choose by measuring against the CPU core count.
Using the community.general.redis cache reports an error: missing the Python redis library (error text varies by collection version; keywords "redis" + "python module/library is required")
Cause: The redis cache plugin runs on the control node, and requires that the Python environment used by ansible has the redis library (when installed via pipx, the environment is isolated).
Fix:pipx inject ansible redis, or in the execution environment (EE)'s requirements.txt add redis.
After enabling the fact cache, Gathering Facts still runs every time
Cause:gathering is still the default implicit; or fact_caching_connection directory is not writable; or the cache has exceeded its timeout.
ansible-config dump --only-changed | grep -iE 'gather|cache' ls -la ./.facts_cache | head
Fix: Set gathering = smart; confirm the directory permissions; note that gather_facts: true when written in the play, smart mode still skips hosts that are already cached.
Raising forks from 30 to 100 did not change the total time
Cause: there are ≤ 30 hosts; the play uses serial; a key task sets throttle; or the bottleneck is one slow host (the linear barrier) or control-node CPU.
grep -rnE 'serial:|throttle:|strategy:' *.yml roles/ 2>/dev/null; top -b -n1 | head -15
Fix: see Module 5 (free strategy, async); use profile_tasks to find the real long-tail task.
1. Without changing configuration files, run perf.yml with forks=40, pipelining enabled, and profile_tasks and timer enabled.
ANSIBLE_PIPELINING=True ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer \ ansible-playbook perf.yml -i inventory/scale.ini -f 40
2. Collect only the minimal facts plus network facts for h01, and display the default IPv4 address.
ansible h01 -i inventory/scale.ini -m ansible.builtin.setup -a 'gather_subset=!all,min,network filter=ansible_default_ipv4'
Your control node is in canadacentral and the managed nodes are in eastasia (RTT about 200 ms), 500 hosts, 30 tasks per playbook. Rank the optimization options by benefit and estimate the gain from pipelining.
Without pipelining each task takes about 5–6 round-trips ≈ 1–1.2 s of pure network latency; with it, about 0.2 s. 30 tasks save about 25–30 s per host, and with forks=50 in 10 batches the total saving is about 4–5 minutes (file transfer not yet counted). Ranking: ① deploy the control node or AWX execution node in the same region (biggest gain, eliminates the RTT itself); ② pipelining; ③ minimize facts + caching; ④ extend ControlPersist to cover the whole playbook; ⑤ raise forks according to control-node resources; ⑥ merge loop tasks (pass a list in one go).
Verified teaching videos
No video verified via oEmbed that specifically explains pipelining, fact caching or profile_tasks was found.
Official documentation
- Controlling playbook execution: strategies and more (forks, serial, throttle)
- ansible.posix.profile_tasks
- ansible.builtin.jsonfile cache
- ansible.builtin.setup (gather_subset)
Video storyboard script (about 100 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: the sorted profile_tasks table, with Gathering Facts ranked first, highlighted in red.
Narration: measure before optimizing. Turn on profile tasks and timer to see where the time actually goes.
Scene: on the left, six small envelopes go back and forth one by one; on the right, one large envelope is delivered at once; the timers show three hundred milliseconds and fifty milliseconds respectively.
Narration: without pipelining, a task needs five to six round-trips and writes temp files; with it enabled, the module is delivered once through standard input.
Scene: 30 hosts arranged in a grid; with forks at 5 they light up in 6 batches, and at 30 they all light up at once.
Narration: forks determines how many hosts are handled at the same time; the number of batches equals the number of hosts divided by forks, rounded up.
Scene: the facts cache folder appears; on the second run the Gathering Facts line disappears, and the total time drops from sixty seconds to under ten.
Narration: minimize facts, and use smart with caching to reuse them across runs. Change one variable at a time and prove the effect with data.
Module 5 · Execution strategies and async/poll
- Compare
linear(default),free,host_pinned— the scheduling methods and use cases of the three strategies. - Distinguish the effects of
forks,serial,throttle,run_once, andorderon concurrency. - Use
async+pollto handle long tasks, and usepoll: 0+ansible.builtin.async_statusto achieve “fire and poll” parallelism.
What: strategy plugins
The strategy plugin decides how tasks are assigned to hosts. ansible-core 2.21 ships with four: linear,free,host_pinned,debug (Module 2). Use the strategy: keyword on a play, or set the global [defaults] strategy / ANSIBLE_STRATEGY setting.
| Strategy | Scheduling method | Advantages | Drawbacks / notes |
|---|---|---|---|
| linear (default) | After all hosts finish task N (batched by forks), they all enter task N+1 together | ordered, easy-to-read output; handlers and run_once semantics are clear | a slow host slows down all hosts |
| free | each host runs its next task as soon as possible, without waiting for other hosts | the shortest total time when host speeds differ widely | interleaved output; logic that depends on “other hosts have finished some step” will break; run_once different behavior |
| host_pinned | like free, but once a worker starts on a host it is pinned until all tasks for that host complete, then it moves on to the next host | the number of hosts processed at once is always forks; suitable for scenarios where you need to limit how many hosts are changing at the same time | later hosts must wait until earlier hosts have completely finished |
How: concurrency control keywords
| Keyword | Scope | Meaning |
|---|---|---|
forks | Global (config / -f) | upper limit of concurrently running workers |
serial | play | splits hosts into batches (by count, percentage or a list such as [1, 5, "20%"]); the whole play finishes one batch before starting the next—rolling update (Lesson 6) |
throttle | task / block | the maximum number of hosts this task runs on at once (cannot exceed forks/serial); suitable for calling rate-limited APIs or shared storage |
run_once | task | runs only on the first host of the current batch, with the result shared to all hosts (used with delegate_to) |
order | play | host order: inventory (default),reverse_inventory,sorted,reverse_sorted,shuffle |
max_fail_percentage / any_errors_fatal | play | failure-percentage threshold / abort when any failure occurs |
How: async and poll
async: N: the module runs in the background on the remote host for at most N seconds; after Ansible disconnects SSH it keeps running, and progress is written to the remote~/.ansible_async/<jid>(ANSIBLE_ASYNC_DIR).poll: M(M>0, default 15): Ansible comes back every M seconds to check, until it finishes or exceeds N seconds. The task still blocks, but this avoids a long single SSH session being cut off by a firewall or idle timeout.poll: 0: “fire and forget”, the task returns immediatelyansible_job_id, the playbook moves on to the next task. Later, useansible.builtin.async_status(jid,until: job.finished+retries/delay) to collect the results, and finallymode: cleanupclean up the state files.- Typical uses: running a 10-minute database backup or image pull on many hosts at the same time; starting several mutually independent long tasks on the same host in parallel (e.g. loop + async).
poll: 0 async tasks should not operate on resources that require exclusive locks (for example, two parallel apt/yum tasks compete for the package manager lock); do not rely on async for scenarios that require check_mode exact results; if the playbook exits before async tasks finish, the background process keeps running up to the async limit.When: how to choose
- Default is linear; use free only when there are no cross-host dependencies between tasks and host speeds differ noticeably.
- When you need “at most N hosts being changed at any moment” without waiting in batches, use host_pinned + forks=N.
- When you need “one canary first, then 10%, then all”, use serial (a dimension outside strategy).
- When calling externally rate-limited APIs (e.g. DNS, load balancers), add
throttle: 1or2on that task.
Comparison with similar techniques
| Ansible | Kubernetes Deployment | Terraform | |
|---|---|---|---|
| Batching | serial | maxSurge/maxUnavailable | None (dependency-graph concurrency) |
| does not wait for slow nodes | strategy: free | controllers in each Pod are independent | dependency graph is naturally concurrent |
| background long-running tasks | async/async_status | Job | Resources timeouts block |
throttle can raise concurrency”—it can only lower it, not exceed forks or serial. ③ “poll: 0 tasks wait for completion automatically”—no; you must collect them with async_status, otherwise you don't know whether they succeeded. ④ “Under free, handlers run once all hosts are done”—handlers still run per host at the end of its play (or when meta: flush_handlers is triggered), so output timing differs from linear.Gantt chart: same 4 hosts, 3 tasks, forks=4, three strategies
Flow diagram: poll: 0 + async_status
Core animation: forks × strategy execution timeline simulator
Set forks, choose a strategy, and optionally mark a host as a “slow host” (time ×3). The simulator generates the Gantt chart using the real scheduling rules: linear synchronizes at the end of each task; in free, an idle worker immediately picks up the next task of any unfinished host; in host_pinned, a worker finishes an entire host before switching to another. The log shows profile_tasks style timings and worker assignments.
Core commands and syntax
| Syntax | Purpose | Notes |
|---|---|---|
strategy: free | play-level strategy | or ANSIBLE_STRATEGY=free |
throttle: 2 | task concurrency limit | also usable on block |
async: 600 + poll: 0 | run in background | return ansible_job_id |
ansible.builtin.async_status | query / clean up | jid,mode: status|cleanup |
ansible-doc -t strategy -l | list strategy plugins | includes third-party strategies from collections |
ansible all -B 600 -P 0 -a 'cmd' | ad-hoc background task | -B= async,-P=poll |
- name: strategy demo
hosts: scale
gather_facts: false
# switch strategy via the environment variable ANSIBLE_STRATEGY for comparison
tasks:
- name: t1 short
ansible.builtin.command: sleep 1
changed_when: false
- name: t2 uneven (h04/h14/h24 slow)
ansible.builtin.command: "sleep {{ 6 if inventory_hostname in ['h04','h14','h24'] else 1 }}"
changed_when: false
- name: t3 rate-limited API
ansible.builtin.command: sleep 1
changed_when: false
throttle: 5
- name: t4 short
ansible.builtin.command: sleep 1
changed_when: false
for s in linear free host_pinned; do
rm -f ~/.ansible/cp/*
echo "== $s"; ANSIBLE_STRATEGY=$s ANSIBLE_CALLBACKS_ENABLED=ansible.posix.timer \
ansible-playbook strat.yml -i inventory/scale.ini -f 10 | tail -1
done
== linear Playbook run took 0 days, 0 hours, 0 minutes, 31 seconds == free Playbook run took 0 days, 0 hours, 0 minutes, 19 seconds == host_pinned Playbook run took 0 days, 0 hours, 0 minutes, 22 seconds
Switching strategy via environment variable avoids editing YAML; when the play already sets the strategy: keyword, the keyword takes precedence over the environment variable. How to verify: When running free, results from different tasks interleave in the output.
async: parallel long tasks
- name: async demo
hosts: lab
gather_facts: false
tasks:
- name: start long job (simulated backup, 20s)
ansible.builtin.shell: "sleep 20 && echo backup-{{ inventory_hostname }} done"
async: 120
poll: 0
register: backup_job
- name: meanwhile do other work
ansible.builtin.debug:
msg: "job id {{ backup_job.ansible_job_id }} started; continuing…"
- name: wait for job
ansible.builtin.async_status:
jid: "{{ backup_job.ansible_job_id }}"
register: job_result
until: job_result.finished
retries: 30
delay: 2
- name: show output
ansible.builtin.debug:
var: job_result.stdout
- name: cleanup async status file
ansible.builtin.async_status:
jid: "{{ backup_job.ansible_job_id }}"
mode: cleanup
time ansible-playbook async.yml
TASK [start long job (simulated backup, 20s)] **********************************
changed: [node1]
changed: [node2]
changed: [node3]
TASK [meanwhile do other work] ************************************************
ok: [node1] => {"msg": "job id j184562338152.4127 started; continuing…"}
…
TASK [wait for job] ***********************************************************
FAILED - RETRYING: [node1]: wait for job (30 retries left).
…
ok: [node1]
TASK [show output] ************************************************************
ok: [node1] => {"job_result.stdout": "backup-node1 done"}
real 0m24.8s
3 hosts run in parallel; the total time is roughly the duration of a single task, not 3 times. Common mistakes: forgetting register or writing a field name wrong in until ; an async limit (120) smaller than the actual duration will cause the task to be killed,async_status return "msg": "Timeout exceeded" class error.
ad-hoc background task
ansible lab -B 300 -P 0 -a 'sleep 30' ansible node1 -m ansible.builtin.async_status -a 'jid=j123456789.1234'
Experiment 5: strategy comparison + parallel long tasks (about 7 minutes)
strat.yml, run the three strategies with -f 10 and -f 30 , recording 6 timestamps into bench.txt:
for f in 10 30; do for s in linear free host_pinned; do
rm -f ~/.ansible/cp/*
t=$( { TIMEFORMAT=%R; time ANSIBLE_STRATEGY=$s ansible-playbook strat.yml -i inventory/scale.ini -f $f >/dev/null; } 2>&1 )
echo "strategy=$s forks=$f ${t}s" | tee -a bench.txt
done; done
strategy=linear forks=10 31.2s strategy=free forks=10 19.6s strategy=host_pinned forks=10 22.4s strategy=linear forks=30 12.8s strategy=free forks=30 11.9s strategy=host_pinned forks=30 12.1s
When forks ≥ number of hosts, the differences between the three strategies shrink (everyone starts at once); the remaining gap comes from slow hosts and throttle.
-f 30 -v , and observe t3 only 5 hosts output results at a time. Change throttle: 5 to 1, and t3 should take close to 30 seconds.async.yml, then change poll: 0 to poll: 5, delete the two following async_status tasks and run again, and compare the total time (three hosts still run in parallel because under linear the same task already runs concurrently across hosts; the difference is that with poll: 0 the intermediate tasks can execute at the same time).ansible node1 -m shell -a 'ls -l ~/.ansible_async/ 2>/dev/null | tail -3'
After cleanup, the file for the corresponding jid disappears; old files without cleanup remain indefinitely.
ansible lab -m shell -a 'rm -rf ~/.ansible_async' -o
Case 1: configuration push across a mixed-hardware cluster
Problem: The same group contains both high-spec physical machines and low-spec edge devices; under the linear strategy, each step costs edge devices an extra 5–10 seconds, so the group push takes 40 minutes. Approach: The tasks in this play have no cross-host dependencies, so switched to strategy: free; steps that need consistency (removing from the load balancer before a reboot) are split into a separate linear play. Limitations: free output is interleaved, so use the JSON callback or ARA to view the complete timeline of each host (Module 6).
Case 2: DNS API is rate-limited
Problem: A task that batch-creates DNS records triggers the provider API's 429 rate limit when forks=50. Approach: add to this task throttle: 3, and add retries/until to handle sporadic 429s; or switch to run_once + a single batch API call. Limitations: throttle is a limit within each play; multiple jobs running in parallel will still stack up.
Case 3: 200 databases backed up at the same time overnight
Problem: Each backup takes 15–40 minutes, and the SSH session is cut off by the firewall's 30-minute idle timeout, causing failures. Approach:async: 3600, poll: 60 Have Ansible poll with short connections every minute; combined with serial: 20 to control storage bandwidth pressure. Limitations: async tasks run on the remote host as the connecting user (or the become user), and the state file is written under its home; if home is full or not writable, async will fail.
Common errors and fixes
fatal: [node1]: FAILED! => {"ansible_job_id": "j…", "changed": false, "finished": 1, "msg": "Timeout exceeded"} (or a similar async timeout message)
Cause: the actual duration exceeded the async limit; async_wrapper killed the module.
Fix: increase async; when using poll: 0 ,retries × delay must also be greater than the actual duration.
fatal: [node1]: FAILED! => {"msg": "could not find job", "started": 1, "finished": 1, "ansible_job_id": "j…"}
Cause: async_status is queried on the wrong host or as the wrong user (e.g. the task was started with become: true but the query was not; the state file is under root's home); or it has already been cleaned up.
ansible node1 -b -m shell -a 'ls ~root/.ansible_async ~ansible/.ansible_async 2>&1'
Fix: keep the become setting of async_status consistent with the one used to start the task.
Under the free strategy: “E: Could not get lock /var/lib/dpkg/lock-frontend”
Cause: two package-management tasks ran in parallel on the same host (for example, an apt started with poll: 0 conflicts with a later apt).
Fix: Do not run package-management tasks asynchronously and concurrently; the apt module can set lock_timeout; merge them into one install list.
A run_once task ran multiple times under the free strategy / the result differs from expectations
Cause: under the free strategy there is no global sync point, so the “first host” semantics of run_once differ from linear; with serial it runs once per batch.
Fix: Put the steps that must run only once into a separate linear play, or run them in a hosts: localhost play.
throttle: 20 is set, but with forks=5 there are still only 5 concurrent hosts
Cause: throttle can only lower concurrency; the upper limit is still determined by forks / serial.
Fix: increase forks.
1. Use ad-hoc to run sleep 60 in the background on the lab group for at most 120 seconds without waiting; then query the status of that task on node1.
ansible lab -B 120 -P 0 -a 'sleep 60' ansible node1 -m ansible.builtin.async_status -a 'jid=<ansible_job_id from the previous step>'
2. Without changing YAML, run strat.yml with the free strategy and 20 forks.
ANSIBLE_STRATEGY=free ansible-playbook strat.yml -i inventory/scale.ini -f 20
A play needs to run on 100 web servers: ① remove from the load balancer ② upgrade the application ③ health check ④ add back to the load balancer. A colleague suggests using strategy: free to speed it up. Do you agree? Give a better plan.
Using free directly is not recommended: under free each host advances independently, so many hosts may be in the “removed” state at the same time, causing insufficient capacity; calling the load balancer API for remove/add may also be overwhelmed by concurrency. A better plan: serial: [1, "10%", "25%"] control the proportion of simultaneous changes (Lesson 6), and use delegate_to + throttle for the remove/add tasks; if you want “at most N hosts changing at any moment without waiting in batches”, consider host_pinned + forks: N, and combine it with max_fail_percentage.
Verified teaching videos
No video verified via oEmbed that specifically explains the strategy plugin and async/poll was found.
Official documentation
- Controlling playbook execution: strategies and more
- Asynchronous actions and polling
- ansible.builtin.async_status
- ansible.builtin.host_pinned
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: four swim lanes, one of them very long; a vertical line at the end of each task, with three short lanes idling before the line.
Narration: the default linear strategy synchronizes at the end of each task; the slowest host sets everyone's pace.
Scene: the vertical lines disappear, and the short lanes move forward and finish early.
Narration: the free strategy lets each host advance as fast as possible; it suits scenarios with no cross-host dependencies between tasks.
Scene: two workers each hold on to a host, finishing it before switching to the next.
Narration: host_pinned keeps a worker pinned to a host until it completes, so you can control how many hosts are being changed at the same time.
Scene: a rocket-launch icon for poll 0, then a radar icon for async status polling, and finally a broom icon for cleanup.
Narration: long tasks use async and poll 0 to launch, you keep doing other things, and finally use async status to collect the results and clean up.
Module 6 · Callback plugins and log auditing
- Understand the event model of callback plugins (
v2_playbook_on_task_start,v2_runner_on_ok/failed/unreachable,v2_playbook_on_stats…) and the rule of “one stdout callback + several notification-type callbacks”. - Switch the stdout callback (
default+result_format=yaml,minimal,ansible.posix.json/jsonl), and use jq to analyze JSON results. - Configure
log_path,log_verbosity, and useno_logcorrectly to keep secrets out of logs. - Use ARA to record each run, forming a searchable audit history.
What: callback plugins
During ansible-playbook execution, the TaskQueueManager broadcasts every event (play start, task start, per-host result, statistics) to all loaded callback plugins. Callback plugins fall into two categories:
| Type | Count | Configuration | Examples |
|---|---|---|---|
stdout (CALLBACK_TYPE = 'stdout') | only one | stdout_callback / ANSIBLE_STDOUT_CALLBACK (default default) | default,minimal,ansible.posix.json,ansible.posix.jsonl,ansible.posix.debug,oneline (deprecated) |
| notification / aggregate | any number | callbacks_enabled / ANSIBLE_CALLBACKS_ENABLED (some plugins set CALLBACK_NEEDS_ENABLED) | ansible.posix.profile_tasks,timer,ansible.builtin.junit, ARA,community.general various notification plugins in |
Verified 2026-11: the callbacks built into ansible-core 2.21 are default,junit,minimal,oneline (deprecated),tree (deprecated); ansible.posix the 2.2.x collection provides cgroup_perf_recap,debug,json,jsonl,profile_roles,profile_tasks,timer. community.general.yaml Removed in community.general 12.0.0; the replacement is default callback's result_format = yaml (since core 2.13).
Why: why care
- Readability:
result_format=yaml+pretty_resultsmake multi-line stdout and diffs easier to read. - Analyzable: JSON output can be analyzed with jq / Python to count failed hosts and slow tasks, and to feed monitoring or ticketing systems.
- Auditing and compliance: who did what to which hosts, when, and with what result—
log_path, ARA, AWX job history. - CI integration:
junitcallbacks turn each task into a test case shown in GitHub Actions / Azure Pipelines.
How: key configuration
| Setting | ini / env var | Description |
|---|---|---|
| Result format | [defaults] callback_result_format = yaml / ANSIBLE_CALLBACK_RESULT_FORMAT | default options for the callback, json (default) or yaml |
| hide ok/skipped | display_ok_hosts,display_skipped_hosts | in large runs, only show changed/failed |
| display arguments | display_args_to_stdout (default False) | show arguments in task titles (beware of secrets) |
| log file | log_path / ANSIBLE_LOG_PATH | not recorded by default; the recorded content is similar to screen output, with timestamp, PID and user |
| log level | log_verbosity / ANSIBLE_LOG_VERBOSITY (since 2.17) | only takes effect above the screen verbosity: screen -v, log -vvv |
| JUnit | JUNIT_OUTPUT_DIR and other env vars | ansible.builtin.junit |
| custom stats | show_custom_stats | displays set_stats data |
no_log: true: task results are replaced with "censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result", and are not written to log_path / syslog. But it cannot protect what you print on debug,-vvvv connection command lines; every loop item is hidden; failures are also hidden, so during troubleshooting, temporarily remove it or use no_log: "{{ hide_secrets | default(true) }}".
How: ARA
ARA (ARA Records Ansible; latest on PyPI is 1.8.0, project hosted on Codeberg) is a callback plugin + Django REST API + web UI. By default it records each run to a local SQLite database (~/.ara/server/ansible.sqlite), and it can also send results to a central API server (container image recordsansible/ara-api); the backend can use MySQL/PostgreSQL. Recorded content: playbook, play, task, each host's result, file contents, facts, parameters and durations. Usable in AWX, ansible-navigator, Molecule and CI (ara must be installed in the same Python environment as Ansible).
When: recommended combinations
- Interactive terminal:
default+result_format=yaml+ profile_tasks. - CI:
default(for readability) +junit, oransible.posix.jsonoutput to a file for post-processing. - Auditing:
log_path(simple), ARA (searchable), AWX/AAP (platform-level, Lesson 5).
Comparison with similar techniques
| Ansible callbacks | Terraform | Kubernetes | |
|---|---|---|---|
| machine-readable output | ansible.posix.json/jsonl | -json,terraform show -json | -o json, Events API |
| Audit history | log_path / ARA / AWX | HCP Terraform runs | audit log (apiserver) |
| Extension point | callback plugins (Python) | no pluggable output | Webhook / audit backend |
callbacks_enabled written json outputs JSON”—json is a stdout-type callback and must be enabled with stdout_callback. ② “ANSIBLE_STDOUT_CALLBACK=json also applies to ad-hoc commands”—ad-hoc does not load the stdout callback config by default, so you must additionally set ANSIBLE_LOAD_CALLBACK_PLUGINS=True (bin_ansible_callbacks). ③ “log_path records only failures”—it records all output. ④ “no_log makes secrets absolutely safe”—secrets still exist in control-node memory, vault files and on the remote host (e.g. written config files); no_log only governs output.Architecture diagram: one event stream, several consumers
Event order (one play, one task, two hosts)
Interaction: the same run, five callback outputs
Below is the same run of 3 tasks × 2 hosts (the 3rd task fails on node2). Click the buttons to switch the stdout callback and observe the output shape; the “event replay” button plays the callback events one by one in the real order and shows which plugins consume each event.
Core commands and configuration
| Command / configuration | Purpose | Notes |
|---|---|---|
ansible-doc -t callback -l | List available callbacks | includes callbacks from collections |
ansible-doc -t callback ansible.posix.json | View callback options | e.g. json_indent |
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json | JSON output | stdout contains only JSON (warnings go to stderr) |
ANSIBLE_CALLBACK_RESULT_FORMAT=yaml | YAML result format | default callback |
ANSIBLE_LOG_PATH=./ansible.log | write a log file | pay attention to file permissions and rotation |
ANSIBLE_LOAD_CALLBACK_PLUGINS=True | ad-hoc also loads the callback | configuration option bin_ansible_callbacks |
YAML result format
ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ansible-playbook site.yml --limit node1 -v | sed -n '/render config/,/^$/p'
TASK [render config (template layer)] *****************************************
ok: [node1] =>
changed: false
checksum: 5f0b…
dest: /tmp/myapp.conf
gid: 1000
mode: '0644'
…
JSON output + jq analysis
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ansible-playbook site.yml > run.json jq '.stats' run.json jq -r '.plays[].tasks[] | [.task.name, .task.duration.start, .task.duration.end] | @tsv' run.json jq -r '.plays[].tasks[] | .task.name as $t | .hosts | to_entries[] | select(.value.failed==true) | "\($t)\t\(.key)\t\(.value.msg)"' run.json
{
"node1": { "changed": 0, "failures": 0, "ignored": 0, "ok": 4, "rescued": 0, "skipped": 0, "unreachable": 0 },
"node2": { "changed": 0, "failures": 0, "ignored": 0, "ok": 4, "rescued": 0, "skipped": 0, "unreachable": 0 }
}
connectivity 2026-11-15T10:41:02.118Z 2026-11-15T10:41:02.903Z
render config (template layer) 2026-11-15T10:41:02.915Z 2026-11-15T10:41:03.601Z
…
How to verify:jq empty run.json No output means it is valid JSON. Common mistakes: redirecting stderr into the file as well (&>) causes warnings to mix into the JSON. Production use: In CI, automatically write the list of failed hosts into a ticket or chat notification.
JSON Lines (streaming)
ANSIBLE_STDOUT_CALLBACK=ansible.posix.jsonl ansible-playbook site.yml | jq -c 'select(._event=="v2_runner_on_failed" or ._event=="v2_runner_on_ok") | {e:._event, h:(.hosts|keys)}' | head
jsonl outputs one line per event; the event field names follow ansible-doc -t callback ansible.posix.jsonl and the actual output.
Log file and audit information
[defaults] log_path = ./logs/ansible.log log_verbosity = 2 ; default screen output; the log records at -vv (2.17+) callback_result_format = yaml display_skipped_hosts = False
mkdir -p logs; ansible-playbook site.yml >/dev/null; tail -4 logs/ansible.log
2026-11-15 10:44:51,201 p=52310 u=azureuser n=ansible INFO| TASK [run as unprivileged appsvc (become to non-root)] ************************* 2026-11-15 10:44:51,733 p=52310 u=azureuser n=ansible INFO| ok: [node1] 2026-11-15 10:44:51,740 p=52310 u=azureuser n=ansible INFO| PLAY RECAP ********************************************************************* 2026-11-15 10:44:51,740 p=52310 u=azureuser n=ansible INFO| node1 : ok=4 changed=0 unreachable=0 failed=0 …
The log line format (fields and level markers) varies slightly between versions; follow the actual output. In production, manage it with logrotate and set 0600 permissions.
no_log
- name: set app password
ansible.builtin.copy:
dest: /tmp/secret.txt
content: "{{ app_password }}"
mode: "0600"
no_log: "{{ hide_secrets | default(true) }}"
ok: [node1] => {"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result", "changed": false}
ARA
pipx inject ansible "ara[server]" PYBIN=$(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python export ANSIBLE_CALLBACK_PLUGINS="$($PYBIN -m ara.setup.callback_plugins)" ansible-playbook site.yml $(dirname $PYBIN)/ara playbook list $(dirname $PYBIN)/ara result list --status failed $(dirname $PYBIN)/ara-manage runserver 0.0.0.0:8000 # open http://control-node:8000 in a browser
+----+-----------+-----------+-----------------+----------+-------+-------+----------+ | id | status | controller| path | started | hosts | tasks | duration | +----+-----------+-----------+-----------------+----------+-------+-------+----------+ | 1 | completed | lab-vm | …/part7/site.yml| 2026-11… | 2 | 5 | 00:00:04 | +----+-----------+-----------+-----------------+----------+-------+-------+----------+
Table column names follow the actual version. Centralized deployment: docker run -d --name ara-api -v ~/.ara/server:/opt/ara -p 8000:8000 docker.io/recordsansible/ara-api:latest, set the client's ARA_API_CLIENT=http,ARA_API_SERVER=http://127.0.0.1:8000. Security:runserver is a development server with no authentication by default; on an Azure VM do not expose port 8000 to the public internet (use an SSH tunnel ssh -L 8000:localhost:8000).
Experiment 6: JSON statistics + logs + ARA (about 6 minutes)
./faults.sh 8 && sed -i 's/^ app_port: 8000/# app_port: 8000/' site.yml
We comment out app_port in site.yml, making the templating layer fail (the group_vars written by fault 8 also lack app_port).
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ansible-playbook site.yml > run.json; echo "rc=$?" jq -r '.stats | to_entries[] | "\(.key) ok=\(.value.ok) failed=\(.value.failures)"' run.json jq -r '.plays[].tasks[] | .task.name as $t | .hosts | to_entries[] | select(.value.failed) | "\(.key): \($t): \(.value.msg)"' run.json
rc=2 node1 ok=1 failed=1 node2 ok=1 failed=1 node1: render config (template layer): The task includes an option with an undefined variable. The error was: 'app_port' is undefined …
ansible-playbook exit codes: 0 = success; 2 = some hosts failed; 4 = some hosts unreachable; for other values see the official docs. CI should judge pass/fail by the exit code.
log_path configuration, then after the run grep -n 'fatal' logs/ansible.log.ara result list --status failed, then use ara result show <id> to view failure details; open the web UI through an SSH tunnel and view render config 's parameters and results.sed -i 's/^# app_port: 8000/ app_port: 8000/' site.yml; ./faults.sh reset rm -f run.json; unset ANSIBLE_CALLBACK_PLUGINS
Case 1: change auditing requires “who, when, and what changed”
Problem: Audit requires automation change records to be kept for 1 year; the team was running ansible-playbook directly in Jenkins, and the logs were lost when builds were cleaned up. Approach: Deploy a centralized ARA API (PostgreSQL backend), inject the ARA callback into the Jenkins execution environment, and record the ticket number and operator via ara_default 's label/metadata feature (see the ARA docs for the specific settings). Limitations: ARA records parameters and file contents, so it must be combined with no_log and ARA's ignore configuration to keep secrets out of storage; in the long run it can be migrated to AWX/AAP.
Case 2: nightly job failures automatically open tickets
Problem: When the nightly compliance-scan playbook fails, someone has to dig through the logs by hand. Approach: Use ansible.posix.json output; a CI script uses jq to extract the failed hosts, task and msg, and calls the ticketing system API to open a ticket; also use the junit callback to show failed cases in CI. Limitations: The json callback only outputs at the end of the playbook; for scenarios needing real-time results, use jsonl streaming.
Case 3: log leaks database password
Problem: A security scan found plaintext passwords in /var/log/ansible.log : a task used shell: mysql -p{{ db_pass }} … and printed cmd on failure. Approach: Add no_log to that task; switch to the community.mysql module (the password field in its parameters is marked as no_log); change the log file permissions to 0600 and clean up historical logs. Limitations: Fields marked in the module argument spec no_log=True are automatically masked, but command lines built by shell/command concatenation are not.
Common errors and fixes
[WARNING]: Could not load 'ansible.posix.json' callback plugin / Invalid callback for stdout specified: json
Cause: ansible.posix is not installed; or the stdout callback was written into callbacks_enabled.
ansible-doc -t callback -l | grep -E '^ansible.posix'
Fix: install the collection; for JSON use stdout_callback.
[DEPRECATION WARNING]: community.general.yaml has been removed / ERROR! Invalid callback for stdout specified: community.general.yaml
Cause: community.general 12.0.0 removed the yaml callback.
Fix:stdout_callback = default + callback_result_format = yaml.
jq: error (at run.json:12): Cannot index string with "stats" / parse error: Invalid numeric literal
Cause: the JSON file is polluted by warning text or -v output (stderr merged,debug callback not switched).
Fix: redirect only stdout; check head -c 200 run.json; do not use interactive arguments such as --step in JSON mode.
[WARNING]: log file at /var/log/ansible.log is not writeable and we cannot create it, aborting
Cause: the current user has no write permission on log_path.
Fix: use a path inside the project, or create the file in advance and grant access: sudo install -m 0640 -o $USER /dev/null /var/log/ansible.log.
ARA recorded no playbooks (ara playbook list is empty)
Cause: ara was installed in a different Python environment from ansible; ANSIBLE_CALLBACK_PLUGINS not exported; ara is not included in AWX/EE.
echo $ANSIBLE_CALLBACK_PLUGINS; ansible-doc -t callback -l | grep -i ara; ansible --version | grep 'python version'
Fix: install with the same interpreter (pipx inject ansible ara); write in ansible.cfg callback_plugins = <path>.
1. Run site.yml with JSON output, and use jq to print the changed count for each host.
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ansible-playbook site.yml | jq -r '.stats | to_entries[] | "\(.key) \(.value.changed)"'
2. Make ad-hoc commands also use the YAML result format and profile_tasks.
ANSIBLE_LOAD_CALLBACK_PLUGINS=True ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks ansible lab -m setup -a 'filter=ansible_hostname'
Security team requirement: all Ansible runs must be auditable (including the operator and ticket number), but no secrets may appear in logs. Design a solution.
① Run everything uniformly in AWX/AAP or a CI executor with ARA, forbidding direct connections to production from personal terminals (credentials only in the platform); ② the operator comes from the platform identity (AWX user / CI trigger), and the ticket number is recorded as an extra var or ARA label; ③ add no_log to all tasks that handle secrets, prefer modules whose argument spec supports no_log, and avoid shell concatenation; ④ give log_path and the ARA database minimal permissions, encrypted storage and a retention period; ⑤ add ansible-lint rules (such as no-log-password) and secret scanning to CI to prevent regressions.
Verified teaching videos
No video verified via oEmbed that specifically explains callback plugins or ARA was found. The ARA project documentation includes an official recorded web interface demo (mp4); see the README for the link.
Official documentation
- Callback plugins
- ansible.builtin.default (result_format and other options)
- ansible.posix.json
- ARA documentation · Codeberg repository
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: one event pipe flows out of Ansible and forks into the terminal, a JSON file, an XML report and a database.
Narration: screen output is just one kind of callback plugin. The same event stream can be sent to several plugins at once.
Scene: the same output switches in turn to default, YAML, condensed and JSON styles.
Narration: there can be only one standard output callback; the JSON callback suits statistics with jq and scripts.
Scene: in the log file, a password line is covered by a black box, with the label no_log: true beside it.
Narration: the log records all output, so tasks that handle secrets must have no_log set.
Scene: the ARA web interface lists past runs; clicking one opens the details of the failed task.
Narration: ARA records each run, turning them into a searchable and shareable audit history.
Module 7 · Custom modules, filters and plugins
- Distinguish modules (run on managed nodes) from plugins (run on the control node: filter, lookup, callback, inventory, connection, action…).
- Use
AnsibleModuleto write an idempotent module:argument_spec,required_if,supports_check_mode,diff,exit_json/fail_json,atomic_move, and fully documentDOCUMENTATION/EXAMPLES/RETURN. - Write a filter plugin and a lookup plugin, and put them in a collection
lab.ops, and call them using FQCN. - Use
ansible-test sanityto check the code and documentation.
What: module vs plugin
| Type | Runs where | Entry point | Typical use | Directory (inside a collection) |
|---|---|---|---|---|
| module | managed node (packaged by AnsiballZ and sent there) | main() + AnsibleModule | changes system state: files, packages, services, API resources | plugins/modules/ |
| module_utils | packaged together with the module | ordinary Python module | code shared by multiple modules | plugins/module_utils/ |
| filter | control node (Jinja2) | class FilterModule: def filters() | data transformation: {{ v | lab.ops.semver_bump('minor') }} | plugins/filter/ |
| test | control node (Jinja2) | class TestModule: def tests() | boolean tests: when: v is lab.ops.semver | plugins/test/ |
| lookup | control node | class LookupModule(LookupBase): def run() | fetch data from outside: files, APIs, secret stores | plugins/lookup/ |
| action | control node (before the module) | ActionBase.run() | logic that needs the control node's involvement (e.g. template renders first, then calls copy) | plugins/action/ |
| callback / inventory / connection / become / cache / strategy | control node | their respective base classes | seen in M3–M6 of this lesson | plugins/<type>/ |
Why: when to write a custom module
- You use
shell/commandincreates,changed_when,failed_when+ regex to simulate idempotency, and the code is becoming increasingly fragile. - You need check mode and diff support (shell cannot truly support it).
- Internal system APIs (CMDB, release platforms) have no ready-made collection.
- The reverse: Search Galaxy and the official collections first, and if an existing module works, don't maintain your own.
How: the responsibilities of AnsibleModule
- Parse parameters: read the arguments injected by AnsiballZ from the
ANSIBLE_MODULE_ARGSand handle type conversion perargument_spec(str/int/bool/list/dict/path/raw), defaults,choices,required,no_log(parameters marked this way are automatically masked in output),aliases. - Parameter relationships:
required_if,required_one_of,mutually_exclusive,required_together,required_by. - check mode Check mode:
supports_check_mode=Truewhenmodule.check_modeis true, the module only computes whether a change would happen, without making it; if the module does not declare support,--checkit is skipped during the run. - Return:
module.exit_json(changed=…, **facts)/module.fail_json(msg=…)print JSON and exit; returndiff(before/after) for--diffto display. - Utility functions:
run_command()(does not go through the shell, avoiding injection),atomic_move(),get_bin_path(),sha256(),warn(),deprecate().
Documentation is the interface: DOCUMENTATION (YAML) describes each option,ansible-doc reads it,ansible-test sanity 's validate-modules checks it against argument_spec for consistency (type, default, choices). EXAMPLES and RETURN are equally required.
How: put it in a collection
collections/ansible_collections/lab/ops/ ├── galaxy.yml # namespace: lab, name: ops, version: 1.0.0 ├── meta/runtime.yml # requires_ansible: ">=2.19.0" ├── plugins/ │ ├── modules/app_release.py │ ├── filter/semver.py # provides semver_bump │ ├── filter/semver_bump.yml # documentation for the filter (optional; read by ansible-doc -t filter) │ └── lookup/kv.py └── tests/ # unit/integration tests (this lesson only does sanity)
In ansible.cfg, add collections_path = ./collections, and you can then call it using FQCN lab.ops.app_release ; for a formal release, run ansible-galaxy collection build to build a tar.gz and publish it to Galaxy / Automation Hub / a private repository. For quick prototypes you can also put modules in a library/ directory next to the playbook, and filters in a filter_plugins/; but for team sharing, use a collection.
When: ansible-test sanity
ansible-test ships with ansible-core and must be run from the …/ansible_collections/<ns>/<name>/ directory. sanity It includes dozens of checks: validate-modules, pylint, pep8, yamllint, compile (syntax for each Python version), import (import isolation), shebang, ansible-doc, and more. Recommended: --docker default (the official test container with all dependencies included); you can also use --venv. When publishing certified content to Galaxy or Automation Hub, passing sanity is a basic requirement.
Comparison with similar techniques
| Ansible modules | Terraform provider | kubectl plugins / Operators | |
|---|---|---|---|
| Language | Python (Windows: PowerShell) | Go (plugin framework) | Any / Go |
| Runs on | managed node | local process (gRPC) | local / in-cluster |
| Idempotency and dry run | implement check_mode/diff yourself | Plan/Apply driven by the framework | Reconcile loop |
slurp/fetch. ③ “A module can simply import requests and that is enough”—dependencies must be installed on the Python of the managed node; otherwise a clear missing-dependency message should be given in fail_json (missing_required_lib). ④ “A module that does not support check mode runs under --check”—no; it is skipped and shows skipped (unless the task explicitly check_mode: false).Architecture diagram: where custom code runs
Development flow
Interaction: module execution lifecycle
Choose an invocation method and step through lab.ops.app_release the full process from task to JSON result: parameter rendering (filter/lookup) → module lookup → AnsiballZ packaging → transfer → parameter validation → check mode branch → return. The log shows the real behavior of each step under -vvv or inside the module.
Core commands
| Command | Purpose | Notes |
|---|---|---|
ansible-galaxy collection init lab.ops --init-path collections/ansible_collections | Generate the collection skeleton | includes galaxy.yml, plugins/, meta/ |
ansible-doc lab.ops.app_release | View module documentation | errors in the documentation YAML are exposed here |
ansible-doc -t lookup lab.ops.kv / -t filter | View plugin documentation | |
ansible-test sanity --docker default -v | Full sanity | run in the collection root directory |
ansible-test sanity --test validate-modules | Run only one check | --list-tests List all |
ansible-galaxy collection build | Build | output lab-ops-1.0.0.tar.gz |
cd ~/ansible-lab/part7 ansible-galaxy collection init lab.ops --init-path collections/ansible_collections # add collections_path in the [defaults] section of ansible.cfg sed -i '/^\[defaults\]/a collections_path = ./collections' ansible.cfg cat > collections/ansible_collections/lab/ops/meta/runtime.yml <<'EOF' --- requires_ansible: ">=2.19.0" EOF
Module: plugins/modules/app_release.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2026, Lab Team
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
module: app_release
short_description: Manage the release marker file of an application
version_added: "1.0.0"
description:
- Records the deployed application version in a marker file.
- Supports check mode and diff mode.
options:
path:
description: Path of the marker file.
type: path
default: /opt/myapp/RELEASE
version:
description: Version string to record. Required when O(state=present).
type: str
state:
description: Whether the marker file should exist.
type: str
choices: [present, absent]
default: present
attributes:
check_mode:
support: full
diff_mode:
support: full
author:
- Lab Team (@labteam)
"""
EXAMPLES = r"""
- name: Record release 1.4.0
lab.ops.app_release:
version: "1.4.0"
- name: Remove marker
lab.ops.app_release:
path: /opt/myapp/RELEASE
state: absent
"""
RETURN = r"""
previous_version:
description: Version found in the marker file before the change.
returned: always
type: str
sample: "1.3.2"
version:
description: Version recorded after the module ran.
returned: always
type: str
sample: "1.4.0"
"""
import os
from ansible.module_utils.basic import AnsibleModule
def read_version(path):
try:
with open(path, encoding="utf-8") as f:
return f.read().strip()
except FileNotFoundError:
return None
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type="path", default="/opt/myapp/RELEASE"),
version=dict(type="str"),
state=dict(type="str", default="present", choices=["present", "absent"]),
),
required_if=[("state", "present", ["version"])],
supports_check_mode=True,
)
path = module.params["path"]
state = module.params["state"]
wanted = module.params["version"]
current = read_version(path)
result = dict(changed=False, path=path, previous_version=current, version=current)
if state == "present" and current != wanted:
result.update(changed=True, version=wanted)
result["diff"] = dict(before_header=path, after_header=path,
before=(current or "") + "\n", after=wanted + "\n")
if not module.check_mode:
parent = os.path.dirname(path)
if parent and not os.path.isdir(parent):
module.fail_json(msg="parent directory %s does not exist" % parent, **result)
tmp = os.path.join(module.tmpdir, "release.tmp")
with open(tmp, "w", encoding="utf-8") as f:
f.write(wanted + "\n")
module.atomic_move(tmp, path)
elif state == "absent" and current is not None:
result.update(changed=True, version=None)
result["diff"] = dict(before=current + "\n", after="")
if not module.check_mode:
os.remove(path)
module.exit_json(**result)
if __name__ == "__main__":
main()
Key points: all changes are placed after if not module.check_mode ; first compute changed, and only then decide whether to act; atomic_move ensures no half-written file is left behind; module.tmpdir is the remote temp directory Ansible provides for this execution (cleaned up automatically when it finishes). O(state=present) is the semantic markup format for ansible-doc.
Local direct invocation (no SSH)
PY=$(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python
cd collections/ansible_collections/lab/ops
echo '{"ANSIBLE_MODULE_ARGS": {"path": "/tmp/RELEASE", "version": "1.4.0", "_ansible_check_mode": true}}' | $PY plugins/modules/app_release.py
echo '{"ANSIBLE_MODULE_ARGS": {"path": "/tmp/RELEASE"}}' | $PY plugins/modules/app_release.py
cd - >/dev/null
{"changed": true, "path": "/tmp/RELEASE", "previous_version": null, "version": "1.4.0", "diff": {…}, "invocation": {"module_args": {…}}}
{"failed": true, "msg": "state is present but all of the following are missing: version", "invocation": {…}}
filter: plugins/filter/semver.py
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.errors import AnsibleFilterError
def semver_bump(version, part="patch"):
"""'1.4.2' | semver_bump('minor') -> '1.5.0'"""
try:
major, minor, patch = (int(x) for x in str(version).lstrip("v").split(".")[:3])
except ValueError as e:
raise AnsibleFilterError("semver_bump: invalid version %r" % (version,)) from e
if part == "major":
return "%d.0.0" % (major + 1)
if part == "minor":
return "%d.%d.0" % (major, minor + 1)
if part == "patch":
return "%d.%d.%d" % (major, minor, patch + 1)
raise AnsibleFilterError("semver_bump: part must be major, minor or patch")
class FilterModule:
def filters(self):
return {"semver_bump": semver_bump}
DOCUMENTATION:
name: semver_bump
version_added: "1.0.0"
short_description: Bump a semantic version
description:
- Increments the major, minor or patch part of a C(X.Y.Z) version string.
positional: part
options:
_input:
description: Version string.
type: str
required: true
part:
description: Which part to bump.
type: str
choices: [major, minor, patch]
default: patch
EXAMPLES: |
next: "{{ '1.4.2' | lab.ops.semver_bump('minor') }}" # 1.5.0
RETURN:
_value:
description: The bumped version.
type: str
lookup: plugins/lookup/kv.py
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
name: kv
author: Lab Team (@labteam)
version_added: "1.0.0"
short_description: Read values from a key=value file on the controller
description:
- Returns the value of each key given as a term from a simple C(key=value) file.
options:
_terms:
description: Keys to look up.
required: true
file:
description: File name, searched in the play/role C(files) search path.
type: str
default: app.env
default:
description: Value returned for missing keys. If not set, a missing key is an error.
type: str
"""
EXAMPLES = r"""
- ansible.builtin.debug:
msg: "{{ lookup('lab.ops.kv', 'APP_VERSION', file='app.env') }}"
"""
RETURN = r"""
_raw:
description: One value per key.
type: list
elements: str
"""
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
self.set_options(var_options=variables, direct=kwargs)
path = self.find_file_in_search_path(variables, "files", self.get_option("file"))
if not path:
raise AnsibleError("kv lookup: file %s not found" % self.get_option("file"))
data = {}
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, value = line.split("=", 1)
data[key.strip()] = value.strip()
default = self.get_option("default")
ret = []
for term in terms:
if term in data:
ret.append(data[term])
elif default is not None:
ret.append(default)
else:
raise AnsibleError("kv lookup: key %s not found in %s" % (term, path))
return ret
Experiment 7: lab.ops collection — module + filter + lookup + sanity (about 8 minutes)
lab.ops, write the three files, then confirm that Ansible can find them:
ansible-galaxy collection list lab.ops ansible-doc lab.ops.app_release | head -12 ansible-doc -t lookup lab.ops.kv | head -5 ansible-doc -t filter lab.ops.semver_bump | head -5
# /home/azureuser/ansible-lab/part7/collections/ansible_collections Collection Version ---------- ------- lab.ops 1.0.0 > MODULE lab.ops.app_release (…/plugins/modules/app_release.py) Records the deployed application version in a marker file. Supports check mode and diff mode. …
APP_VERSION=1.4.2 APP_CHANNEL=stable
- name: release marker
hosts: web
gather_facts: false
become: true
vars:
current: "{{ lookup('lab.ops.kv', 'APP_VERSION') }}"
next_version: "{{ current | lab.ops.semver_bump(bump | default('minor')) }}"
tasks:
- name: ensure dir
ansible.builtin.file:
path: /opt/myapp
state: directory
mode: "0755"
- name: record release
lab.ops.app_release:
version: "{{ next_version }}"
register: rel
- name: show
ansible.builtin.debug:
msg: "{{ rel.previous_version }} -> {{ rel.version }} (changed={{ rel.changed }})"
ansible-playbook release.yml --check --diff # dry run: show the diff, do not write files ansible-playbook release.yml --diff # first run: changed ansible-playbook release.yml # second run: must show changed=0 (idempotent) ansible-playbook release.yml -e bump=major --diff
TASK [record release] **********************************************************
--- before: /opt/myapp/RELEASE
+++ after: /opt/myapp/RELEASE
@@ -1 +1 @@
-
+1.5.0
changed: [node1]
…
ok: [node1] => {"msg": "None -> 1.5.0 (changed=True)"}
… (second run)
ok: [node1] => {"msg": "1.5.0 -> 1.5.0 (changed=False)"}
node1 : ok=3 changed=0 …
Note that on the first run, with --check present, /opt/myapp the directory does not yet exist, but in check mode the module does not write files, so the 'parent directory does not exist' error does not occur—this is the value of computing changed first, then acting.
ANSIBLE_KEEP_REMOTE_FILES=1 ANSIBLE_PIPELINING=False ansible node1 -b -m lab.ops.app_release -a 'version=9.9.9 path=/tmp/R' -vvv | grep -m1 'PUT .*AnsiballZ' docker exec node1 sh -c 'cd $(ls -dt /root/.ansible/tmp/ansible-tmp-* | head -1) && python3 AnsiballZ_app_release.py explode >/dev/null && find debug_dir -name "*.py" | head'
debug_dir/ansible_collections/lab/ops/plugins/modules/app_release.py debug_dir/ansible/module_utils/basic.py debug_dir/ansible/module_utils/common/…
When becoming root, the temp directory is under root's home (the exact location depends on remote_tmp and the become method; if not found, check the PUT lines under -vvv).
cd collections/ansible_collections/lab/ops git init -q && git add -A # ansible-test uses git to decide which files belong to the collection ansible-test sanity --docker default -v --test validate-modules ansible-test sanity --docker default -v 2>&1 | tail -15 cd ~/ansible-lab/part7
Running sanity test "validate-modules"
…
Running sanity test "pylint"
Running sanity test "pep8"
…
(if there are problems it will list file:line:col: error code and description, for example)
ERROR: plugins/modules/app_release.py:0:0: doc-default-does-not-match-spec: Argument 'path' in argument_spec defines default as ('/opt/myapp/RELEASE') but documentation defines default as (None)
The first --docker default run pulls the official test image (large, takes a few minutes). Without Docker, you can use --venv --python 3.12, but some checks need extra dependencies. Deliberately delete the path option in the documentation default and run again to see how validate-modules detects the "documentation does not match argument_spec" mismatch. The generated tests/output/ can be added to .gitignore.
(cd collections/ansible_collections/lab/ops && ansible-galaxy collection build --force) ansible web -b -m file -a 'path=/opt/myapp state=absent' -o
Case 1: replace 40 lines of shell with a module
Problem: The internal release platform registers versions by relying on shell: curl … | jq …, together with changed_when: "'created' in result.stdout", often falsely reports changed, and when --check it skips outright, so dry runs are impossible. Approach: Write a corp.release.version module: GET the current state → compare → POST if necessary; support check mode and diff; mark the token parameter as no_log=True. Configuration: HTTP calls use ansible.module_utils.urls.fetch_url (which handles proxies and TLS verification parameters automatically), and do not depend on requests on the managed node. Limitations: modules that call APIs are often used with delegate_to: localhost , in which case the "managed node" is the control node.
Case 2: a filter plugin standardizes naming
Problem: Each team concatenated resource names in templates with its own Jinja2 expressions; lengths and character sets were inconsistent, causing Azure resource name limits to be exceeded. Approach: The platform team provides a corp.naming.resource_name filter (truncates by resource type, removes illegal characters, appends a hash suffix), along with unit tests. Limitations: Filters run on the control node, so any dependency libraries must be installed on the control node / in the execution environment.
Case 3: sanity finds a Python compatibility problem
Problem: A developer used syntax available only in newer Python in a module; local tests passed, but some managed nodes run Python 3.9. Approach: Run ansible-test sanity --docker default in CI; its compile test compiles the module under every supported Python version, catching the problem early. Limitations: The Python versions supported on managed nodes (3.9–3.14 for 2.21) differ from those on the control node (3.12–3.14): module code should be written for the lowest managed-node version, and plugin code for the control-node version.
Common errors and fixes
ERROR! couldn't resolve module/action 'lab.ops.app_release'. This often indicates a misspelling, missing collection, or incorrect module path.
Cause: collections_path is not configured, or the directory structure is not ansible_collections/lab/ops/plugins/modules/; the file name does not match the module name.
ansible-config dump --only-changed | grep -i collection ansible-galaxy collection list | grep lab find collections -name 'app_release.py'
Fix: set collections_path (note the path must point to the parent directory that contains ansible_collections ).
fatal: [node1]: FAILED! => {"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "module_stdout": "Traceback (most recent call last): … NameError: name 'wanted' is not defined"}
Cause: the module code threw an exception on the remote host without returning through fail_json.
Fix: reproduce with a local JSON invocation; or debug on the remote host with KEEP_REMOTE_FILES + explode; for expected errors, use fail_json(msg=…) to return a clear message.
fatal: [node1]: FAILED! => {"msg": "Unsupported parameters for (lab.ops.app_release) module: verison. Supported parameters include: path, state, version."}
Cause: a parameter was misspelled; AnsibleModule validates automatically.
Fix: correct the spelling; if backward compatibility with an old name is needed, add aliases in argument_spec.
template error while templating string: Could not load "lab.ops.semver_bump": 'Invalid plugin FQCN (lab.ops.semver_bump): unable to locate collection lab.ops'
Cause: the filter file exists but the collection is not visible, or the file does not FilterModule.filters() return that name (note that the FQCN of a filter uses the key in the filters() dictionary, not the file name).
ansible-doc -t filter -l | grep lab.ops
Fix: confirm collections_path and the return value of filters() ; the error text varies slightly between versions.
ERROR: The current working directory must be within the source tree being tested. / Collection path … does not match expected 'ansible_collections/{ns}/{name}'
Cause: ansible-test was not run in the collection root directory, or the directory level is wrong.
Fix:cd collections/ansible_collections/lab/ops then run again.
1. Without SSH, on the control node call the app_release module file with check mode and view the JSON result.
echo '{"ANSIBLE_MODULE_ARGS": {"path": "/tmp/R", "version": "2.0.0", "_ansible_check_mode": true}}' | python3 collections/ansible_collections/lab/ops/plugins/modules/app_release.pypython3 must be able to import ansible (use the interpreter in the virtual environment where ansible is installed).
2. Run only the validate-modules sanity test.
cd collections/ansible_collections/lab/ops && ansible-test sanity --docker default --test validate-modules
A colleague wrote a lookup plugin that reads /etc/app/version, but in the playbook it always returns the version on the control node rather than each server's version. Explain why, and give two correct approaches.
The lookup runs on the control node and reads the control node's files. Correct approaches: ① read the remote file with ansible.builtin.slurp (which returns base64, decoded with the b64decode filter), or command: cat /etc/app/version + register; ② write a custom module (such as a “query mode” for app_release) or a custom fact (/etc/ansible/facts.d/*.fact, obtained via ansible_local ).
Verified teaching videos
Official documentation
- Developing modules
- Developing plugins
- Developing collections
- Sanity Tests
- Module format and documentation
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: a shell + regex chain that keeps getting longer, with changed_when conditions piling up until they collapse.
Narration: when you simulate idempotency with shell and regex, it is time to consider writing a real module.
Scene: AnsibleModule code, with the argument spec, check mode branch and exit json highlighted in turn.
Narration: AnsibleModule handles parameter validation and return format; you only need to work out first whether something will change, then make the real change outside check mode.
Scene: on the control node side, filter and lookup light up; on the managed node side, the module lights up.
Narration: filter and lookup run on the control node, the module runs on the managed node; this determines where dependencies are installed and where files are read from.
Scene: the output of ansible-test sanity; after one documentation-default inconsistency error is fixed, everything passes.
Narration: finally, use ansible-test sanity to check code and documentation; once they are consistent, package and publish.
Module 8 · Comprehensive fault mystery box
- Facing an unknown fault, work in the order: inventory → connection → privilege escalation → module → templating, starting with the cheapest checks, locating the fault with evidence rather than guesses.
- Memorize the “fingerprints” (keywords in the raw error text) of the 8 high-frequency faults and their corresponding fixes.
- Practice with the interactive troubleshooting tree and the browser simulator, then use
faults.sh randomto time the challenge in a real environment.
What: the 8 faults and their fingerprints
| # | Layer | Injection method | Fingerprint (error keywords) | Cheapest evidence | Fix |
|---|---|---|---|---|---|
| 1 | ① Inventory | host_vars changes node2's port to 2299 | UNREACHABLE + port 2299: Connection refused | ansible-inventory --host node2 | delete / correct host_vars |
| 2 | ② Connection | rebuild the container and change the host key | REMOTE HOST IDENTIFICATION HAS CHANGED,Host key verification failed | -m raw -a true -vvvv | after verifying the fingerprint, ssh-keygen -R + re-trust |
| 3 | ③ Privilege escalation | sudo changed to require a password | Missing sudo password | ping works, ping -b fails | -K / the become password in vault / restore NOPASSWD |
| 4 | ④ Module | removes python3.12 | MODULE FAILURE,rc: 127,python3: not found | -m raw -a 'ls -l /usr/bin/python3*' | restore/install Python with raw, or correct the interpreter path |
| 5 | ③ Privilege escalation | requiretty + pipelining enabled | sorry, you must have a tty to run sudo | controlled experiment with pipelining off | remove requiretty from sudoers (or turn pipelining off for that group) |
| 6 | ③ Privilege escalation | uninstall acl | Failed to set permissions on the temporary files … unprivileged user | command -v setfacl | install acl / pipelining / common_remote_group |
| 7 | ② Connection (remote filesystem) | ~/.ansible permissions 000 | UNREACHABLE + Failed to create temporary directory | -m raw -a 'ls -ld ~/.ansible' | fix permissions / set remote_tmp |
| 8 | ⑤ Templating | group_vars lacks app_port (and it is not defined in the play) | 'app_port' is undefined, no SSH EXEC in -vvv | ansible-inventory --host node1 | add the variable / default() / argument_specs |
Note: fault 8 only shows up when the play itself does not define app_port (play vars have higher precedence than group_vars); before the mystery box, prepare as in step 1 of the Experiment page blind.yml, which does not define app_port in the play.
Why: why do the mystery box
In real incidents you don't know “what was injected”, and you often face noise at the same time (other hosts are fine, warnings, leftovers from the last run). The mystery box trains the process: read the raw error → determine the layer → confirm with one command → fix → regression check → record.
How: the 3-minute process
- 0:00–0:30 Read PLAY RECAP: which hosts, UNREACHABLE or FAILED? Only one host or all of them?
- 0:30–1:00 Read the first fatal's
msg/module_stderr, and compare it with the fingerprint table to determine the layer. - 1:00–2:00 Confirm with the cheapest check for that layer (inventory → raw → ping → ping -b → controlled experiment).
- 2:00–3:00 Fix and
--limitregression-check; write a one-sentence root cause.
When: when to escalate
- Errors outside the fingerprint table → single-task -vvv + KEEP_REMOTE_FILES (Module 1).
- Abnormal behavior without errors (slow, hanging) → profile_tasks (Module 4), ANSIBLE_DEBUG, the remote
ps. - Appears only on some hosts → compare the
ansible-inventory --hostand facts of normal hosts.
Comparison with similar techniques
| Ansible mystery box | Chaos Engineering (e.g. Chaos Mesh) | Game Day | |
|---|---|---|---|
| Target | the automation pipeline itself | running applications | team process and communication |
| Purpose | train troubleshooting ability | verify system resilience | verify the response process |
--limit regression-check and verify whether other hosts have the same hidden problem. ③ “host_key_checking=False solves many problems at once”—it only masks fault 2, and introduces a security risk.Fingerprint map: error keyword → layer → fault number
Regression verification loop
In-browser fault simulator
Click “Draw a fault”; the simulator randomly picks one of the 8 faults and displays the ansible-playbook blind.yml output. You can click diagnostic commands to see real-style output (each command counts toward the “diagnostic cost”), then choose the root cause below. Goal: answer correctly with the fewest commands in the shortest time. Scores are kept only on the current page.
Mystery box toolkit (sorted by cost)
| Cost | Command | Question it answers |
|---|---|---|
| 0 (offline) | ansible-inventory --host H,--graph | Are the host and variables correct? |
| 1 | ansible H -m raw -a 'id; ls -ld ~ ~/.ansible; command -v python3 setfacl' | Does SSH work? Are home, Python and acl present? |
| 1 | ansible H -m ping / -b | Are the module layer and privilege layer normal? |
| 2 | ANSIBLE_PIPELINING=False ansible H -m ping -b | Is it related to pipelining? |
| 3 | ansible H -m raw -a true -vvvv | Which step of the SSH handshake fails? |
| 4 | ansible-playbook blind.yml --limit H --start-at-task '…' -vvv | Full details of a specific task |
# One-click “health check”: run layered checks on the lab group and summarize ansible-inventory --host node2 | grep -E 'ansible_(host|port|user)' ansible lab -m raw -a 'echo SSH_OK; ls -ld ~/.ansible 2>&1; command -v python3 setfacl; sudo -n true 2>&1 && echo SUDO_NOPASSWD' -o ansible lab -m ping -o ansible lab -m ping -b -o ANSIBLE_PIPELINING=False ansible lab -m ping -b -o
node1 | CHANGED | rc=0 | (stdout) SSH_OK\r\ndrwxr-xr-x 3 ansible ansible 4096 … /home/ansible/.ansible\r\n/usr/bin/python3\r\n/usr/bin/setfacl\r\nSUDO_NOPASSWD
node2 | CHANGED | rc=0 | (stdout) SSH_OK\r\ndrwxr-xr-x 3 ansible ansible 4096 … /home/ansible/.ansible\r\n/usr/bin/python3\r\n/usr/bin/setfacl\r\nsudo: a password is required
…
node2 | FAILED! => {"msg": "Missing sudo password"}
How to verify: Each line of the health-check script corresponds to one layer; the first line that shows an anomaly is where the root cause lies. Common mistakes: forgetting ./faults.sh reset after a fix and moving on to the next round, so two faults overlap.
Experiment 8: real mystery box (3 rounds, 3 minutes per round)
- name: blind box
hosts: web
gather_facts: false
tasks:
- name: L2 connectivity
ansible.builtin.ping:
- name: L5 template
ansible.builtin.copy:
dest: /tmp/{{ app_name | default('myapp') }}.conf
content: "port={{ app_port }}\n"
mode: "0644"
- name: L3 become root
ansible.builtin.command: id -u
become: true
changed_when: false
- name: L3 become unprivileged
ansible.builtin.command: id -un
become: true
become_user: appsvc
changed_when: false
mkdir -p group_vars; printf 'app_name: myapp\napp_port: 8000\n' > group_vars/web.yml ansible-playbook blind.yml # baseline: all ok
./faults.sh random; date +%T; ansible-playbook blind.yml
Locate using the toolkit from the Commands page; write down “layer + root cause + evidence command”, then ./faults.sh reveal verify. Note: fault 8 will overwrite group_vars/web.yml,reset afterwards you need to re-run the step-1 printf.
ansible-playbook blind.yml --limit node2 it passes only when everything is green; then ./faults.sh reset and restore group_vars.blindbox.md, which the comprehensive lab needs../faults.sh reset; printf 'app_name: myapp\napp_port: 8000\n' > group_vars/web.yml
Case 1: the “five-layer health check” in the on-call handbook
Problem: Different on-call engineers handle the same kind of Ansible fault with a 10× difference in time. Approach: Turn the health-check script from the Commands page into a playbook (using only raw and ping), use it in AWX as a “diagnostic job template”, and automatically attach it to the incident ticket on failure. Limitations: raw output is not structured, so it needs to be parsed with the jsonl callback.
Case 2: quarterly Game Day
Problem: The team rarely encounters connection-layer faults, so they are rusty when one actually happens. Approach: Every quarter, in the pre-production environment, use a script similar to faults.sh to randomly inject 3 faults, time the response, review it afterwards, and add newly discovered fingerprints to the problem bank in Lesson 8. Limitations: The injection script must have a strict target allowlist and reset capability, and must never touch production.
Case 3: baseline image regression test
Problem: The new “minimal image” lacks acl, causing all become_user tasks to fail (the real-world version of fault 6). Approach: Add a smoke test containing only the mystery box playbook to the image pipeline, and run it before the image is released. Limitations: The smoke test only covers known fingerprints; you still need to monitor the first batch of hosts brought online.
Interactive troubleshooting tree: layered localization of Ansible failures
Starting from the symptoms, answer step by step; the troubleshooting tree gives diagnostic commands and fix suggestions (covering the 8 mystery-box faults in this lesson and common variants).
1. Write one command using only the raw module that simultaneously checks SSH, the permissions of .ansible under home, and whether Python and setfacl exist.
ansible lab -m raw -a 'echo SSH_OK; ls -ld ~/.ansible; command -v python3 setfacl' -o
2. Write a controlled command that proves a privilege-escalation failure is related to pipelining.
ANSIBLE_PIPELINING=True ansible node2 -m ping -b -o; ANSIBLE_PIPELINING=False ansible node2 -m ping -b -o
Mystery box output: node1 ok, node2 UNREACHABLE! … Failed to connect to the host via ssh: ssh: connect to host 127.0.0.1 port 2299: Connection refused. A colleague is about to check node2's sshd and firewall. What do you say?
First check the port: in the inventory node2 should be 2222, but the error shows 2299, which means the connection parameters themselves are wrong—this is the inventory/variable layer (fault 1). Run ansible-inventory --host node2 to confirm the final ansible_port, then grep -rn ansible_port host_vars group_vars inventory find the source (host_vars takes precedence over host variables in the inventory). After the fix, --limit node2 regression-check. Checking sshd and the firewall is a far more expensive and unrelated step.
Verified teaching videos
Official documentation
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3; a storyboard and narration script are provided.
Scene: a mystery box is opened, and a line of red error text flies out.
Narration: a fault mystery box: you don't know what was injected, and can only look at the symptoms.
Scene: errors are sorted into two baskets, UNREACHABLE and FAILED, and then sorted by keyword into the five layers.
Narration: first separate unreachable from failed, then use the keywords to find the layer.
Scene: commands are arranged as a ladder by cost: inventory, raw, ping, ping with b, controlled experiment, and four v's.
Narration: start with the cheapest checks, and use one command to confirm your judgment.
Scene: after the fix, the PLAY RECAP is all green, and the root cause and prevention are written in a notebook.
Narration: after fixing, do a regression check and write down the root cause and prevention measures, so next time it's faster.
Command cheat sheet
Layered localization
ansible --version | grep 'config file' ansible-config dump --only-changed ansible-inventory --graph ansible-inventory --host H ansible H -m raw -a 'id; ls -ld ~/.ansible' ansible H -m ping # module layer ansible H -m ping -b # privilege layer ansible H -m raw -a true -vvvv # SSH handshake
Keep and debug remote modules
ANSIBLE_KEEP_REMOTE_FILES=1 ANSIBLE_PIPELINING=False \ ansible H -m MODULE -a '…' -vvv | grep 'PUT .*AnsiballZ' # On the remote host: python3 AnsiballZ_MODULE.py explode vi debug_dir/args python3 AnsiballZ_MODULE.py execute ANSIBLE_DEBUG=1 ansible H -m ping # internal debug log
Playbook debugger
debugger: on_failed # always|never|on_failed|on_unreachable|on_skipped # Global: ANSIBLE_ENABLE_TASK_DEBUGGER=True # Commands: # p task / p task.args / p task_vars / p result._result # task.args['k'] = 'v' → r # task_vars['k'] = 'v' → u → r # c continue q abort
Narrow the scope
ansible-playbook site.yml --syntax-check ansible-playbook site.yml --list-tasks --list-hosts ansible-playbook site.yml --start-at-task 'role : name*' ansible-playbook site.yml --step --check --diff ansible-playbook site.yml --limit node2 --tags deploy
Connection and privilege escalation
ssh-keygen -R '[127.0.0.1]:2222' ssh-keyscan -p 2222 127.0.0.1 >> ~/.ssh/known_hosts for s in ~/.ansible/cp/*; do ssh -O exit -o ControlPath="$s" x; done ansible H -m ping -b -K ansible H -m command -a 'id' -b --become-user appsvc ANSIBLE_PIPELINING=False ansible H -m ping -b # controlled experiment ansible H -m setup -a 'filter=ansible_python*'
Performance configuration
[defaults] forks = 30 gathering = smart fact_caching = jsonfile fact_caching_connection = ./.facts_cache fact_caching_timeout = 7200 callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer [ssh_connection] pipelining = True ssh_args = -C -o ControlMaster=auto -o ControlPersist=10m
Strategy and async
strategy: free # linear | free | host_pinned
serial: [1, "25%"]
tasks:
- command: /opt/long.sh
async: 600
poll: 0
register: j
- async_status: { jid: "{{ j.ansible_job_id }}" }
register: r
until: r.finished
retries: 60
delay: 10
- command: call_api
throttle: 2Callbacks and logging
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ansible-playbook site.yml > run.json jq '.stats' run.json ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ansible-playbook site.yml -v ANSIBLE_LOG_PATH=./ansible.log ANSIBLE_LOG_VERBOSITY=2 ansible-playbook site.yml ANSIBLE_LOAD_CALLBACK_PLUGINS=True ansible lab -m ping # ad-hoc also uses callbacks export ANSIBLE_CALLBACK_PLUGINS="$(python3 -m ara.setup.callback_plugins)"
Plugin development
ansible-galaxy collection init lab.ops --init-path collections/ansible_collections
ansible-doc lab.ops.app_release
ansible-doc -t filter -l | grep lab.ops
echo '{"ANSIBLE_MODULE_ARGS":{"version":"1.0.0","path":"/tmp/R"}}' | python3 plugins/modules/app_release.py
ansible-test sanity --docker default -v
ansible-galaxy collection buildFault injection (lab only)
./faults.sh list ./faults.sh random ./faults.sh reveal ./faults.sh reset
Quick troubleshooting table
| Symptom / error keywords | Layer | First command | Common fixes |
|---|---|---|---|
| Could not match supplied host pattern | Inventory | ansible-inventory --graph | correct group name / ansible.cfg location |
| Connection refused / timed out | Inventory or connection | ansible-inventory --host check port and address | correct variables / network / sshd |
| Permission denied (publickey) | Connection | -m raw -a true -vvvv | user, private key, authorized_keys permissions |
| Host key verification failed | Connection | ssh-keygen -lf verify | ssh-keygen -R + re-trust |
| Failed to create temporary directory | connection / remote FS | -m raw -a 'ls -ld ~/.ansible; df -h' | permissions, disk, remote_tmp |
| Missing sudo password | privilege escalation | -m ping -b | -K / vault / NOPASSWD |
| must have a tty to run sudo | privilege escalation | pipelining control experiment | remove requiretty |
| Failed to set permissions on the temporary files | privilege escalation | command -v setfacl | install acl / pipelining |
| MODULE FAILURE rc 127 | module | -m raw -a 'ls -l /usr/bin/python3*' | install Python / correct the interpreter |
| MODULE FAILURE + Traceback | module | KEEP_REMOTE_FILES + explode | dependency library / module bug |
| 'x' is undefined | templating | ansible-inventory --host,debug: var= | fill in variables / default() / argument_specs |
| the job is very slow | performance | profile_tasks + timer | facts, pipelining, forks, free, async |
| CI stuck at (debug)> | debugger | grep -rn 'debugger:' | remove the keyword / environment variable |
Recommended configuration snippet (production starting point)
[defaults] inventory = inventory/ forks = 50 gathering = smart fact_caching = jsonfile fact_caching_connection = ~/.cache/ansible/facts fact_caching_timeout = 7200 interpreter_python = auto_silent callbacks_enabled = ansible.posix.profile_tasks, ansible.posix.timer callback_result_format = yaml log_path = ~/.cache/ansible/ansible.log host_key_checking = True retry_files_enabled = False [ssh_connection] pipelining = True ; first confirm sudoers does not enable requiretty ssh_args = -C -o ControlMaster=auto -o ControlPersist=10m -o ServerAliveInterval=30 retries = 2
Comprehensive lab + final quiz
inventory/scale.ini), fails intermittently, and takes over a minute. The release review requires: ① fix 3 random faults without knowing their cause in advance, and write the root cause and evidence for each one; ② deliver a performance optimization report: before-and-after timing comparison of the same playbook (at least 4 rounds, changing only one variable per round), with the principle and risk of each optimization explained; ③ archive the run results as JSON and make them searchable in ARA; ④ replace the shell logic in the playbook with a custom module, and pass sanity.cd ~/ansible-lab/part7 ./faults.sh reset; printf 'app_name: myapp\napp_port: 8000\n' > group_vars/web.yml ansible lab -m ping -o; ansible scale -i inventory/scale.ini -m ping -o | grep -c SUCCESS ansible-galaxy collection list | grep -E 'ansible.posix|lab.ops'
node1 | SUCCESS => … node2 | SUCCESS => … node3 | SUCCESS => … 30 ansible.posix 2.2.2 lab.ops 1.0.0
for round in 1 2 3; do ./faults.sh random read -p "Round $round: after locating and fixing, press Enter (do not reveal first)" _ ansible-playbook blind.yml --limit node2 && echo "ROUND $round PASS" ./faults.sh reveal ./faults.sh reset; printf 'app_name: myapp\napp_port: 8000\n' > group_vars/web.yml done
In report.md , record for each round: the raw error fingerprint, the layer determined, the confirmation command, the fix action, the time taken, and the prevention measures.
perf.yml , add a step that records the version; first write a “bad” version for comparison:
# Before optimization: shell version (changed every time; skipped in --check)
- name: record release (shell)
ansible.builtin.shell: "echo 1.5.0 > /tmp/perf/{{ inventory_hostname }}/RELEASE"
# After optimization: module version (idempotent; supports check/diff)
- name: record release (module)
lab.ops.app_release:
path: "/tmp/perf/{{ inventory_hostname }}/RELEASE"
version: "1.5.0"
ansible-playbook perf.yml -i inventory/scale.ini | tail -3 # run twice and compare the changed counts of the two approaches
bench.sh from Module 4:
: > bench.txt; rm -rf .facts_cache ./bench.sh R0-baseline ANSIBLE_FORKS=5 ANSIBLE_PIPELINING=False ./bench.sh R1-forks30 ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=False ./bench.sh R2-pipeline ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ./bench.sh R3-cachewarm ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ANSIBLE_GATHERING=smart ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=./.facts_cache ./bench.sh R4-cachehit ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ANSIBLE_GATHERING=smart ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=./.facts_cache ./bench.sh R5-free ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True ANSIBLE_GATHERING=smart ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=./.facts_cache ANSIBLE_STRATEGY=free cat bench.txt
R0-baseline total= 64.1s facts=22.40s R1-forks30 total= 28.3s facts=8.20s R2-pipeline total= 16.9s facts=5.10s R3-cachewarm total= 16.6s facts=5.05s R4-cachehit total= 9.8s facts=0s R5-free total= 9.1s facts=0s
{
echo "# Performance optimization report: perf.yml (30 hosts)"
echo; echo "| Round | Change | Total time | Facts | vs. baseline |"; echo "|---|---|---|---|---|"
base=$(awk 'NR==1{gsub("total=","",$2); gsub("s","",$2); print $2}' bench.txt)
awk -v b="$base" '{t=$2; gsub("total=","",t); gsub("s","",t); f=$3; gsub("facts=","",f); printf "| %s | %s | %ss | %s | %.0f%% |\n", NR-1, $1, t, f, t/b*100}' bench.txt
echo; echo "Slowest task (after optimization):"; grep -A6 '^=====' bench-R5-free.log | tail -6
} > perf-report.md; cat perf-report.md
For each round in the report, add: the principle (why it got faster), prerequisites and risks (e.g. pipelining requires requiretty to be disabled, fact cache consistency, the effect of the free strategy on cross-host dependencies), and whether it is suitable to enable by default in production.
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ANSIBLE_FORKS=30 ANSIBLE_PIPELINING=True \ ansible-playbook perf.yml -i inventory/scale.ini > perf-final.json jq -r '.stats | to_entries | map(select(.value.failures>0 or .value.unreachable>0)) | length' perf-final.json # should be 0 export ANSIBLE_CALLBACK_PLUGINS="$($(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/python -m ara.setup.callback_plugins)" ansible-playbook perf.yml -i inventory/scale.ini >/dev/null $(pipx environment --value PIPX_LOCAL_VENVS)/ansible/bin/ara playbook list | head -5
(cd collections/ansible_collections/lab/ops && ansible-test sanity --docker default --test validate-modules) ansible scale -i inventory/scale.ini -m file -a 'path=/tmp/perf state=absent' -o >/dev/null ./faults.sh reset # After the experiment, release resources (Azure VM): # docker rm -f node1 node2 node3 # az group delete -n rg-ansible-lab --yes --no-wait # if the lab machine is a VM created specifically for it
The node containers can be kept for Lesson 8 (reproducing production issues).
Open-ended self-test (answer it yourself first, then expand the reference answer)
1. What are the five layers of the five-layer method? Why is “inventory” placed first when troubleshooting?
Inventory, connection, privilege escalation, module, templating. The inventory check is offline and zero-cost (ansible-inventory --host), and inventory/variable errors often masquerade as connection errors (for example, a port overridden by host_vars causes Connection refused).
2. What is the difference between changing task.args and task_vars in the debugger?
task.args holds the already-rendered module parameters; after changing them, enter r to take effect directly. task_vars are variables, and the task was rendered from the old variables, so you need to u (update_task) to re-render it r before running it again.
3. Why does pipelining speed things up? What are its prerequisites and limitations?
The module is sent to the remote Python through SSH stdin: one round-trip, no temp files written (previously home probing, mkdir, sftp, chmod, execution and rm made 5–6 round-trips in total). Prerequisite: sudoers does not enable requiretty. Limitations: actions that need file transfer (copy/template/fetch) and non-Python modules still use the normal path; KEEP_REMOTE_FILES has no file to keep.
4. When becoming a non-privileged user produces a temp-file permissions error, what did Ansible try, in order?
setfacl (POSIX ACL) → chown → chmod +a (macOS) → ansible_common_remote_group (chgrp) → world_readable_temp (if allowed). Pipelining avoids the problem; the most common fix is installing the acl package.
5. Which scenarios suit linear, free and host_pinned? How do forks, serial and throttle interact?
linear: the default, with synchronization between tasks; suits changes with cross-host dependencies and a need for clear output. free: no cross-host dependencies and large differences in host speed. host_pinned: limits the number of hosts changing at once without waiting in batches. forks is the global ceiling; serial splits hosts into batches (within a batch, limited by forks); throttle can only further reduce concurrency on a task or block.
6. How should the check mode of a custom module be implemented? Why must the dependencies of filter/lookup be installed on the control node?
Declare supports_check_mode=True, first read the current state and compute changed and diff, and put all changes after if not module.check_mode the check branch. Filters and lookups run in the Jinja2/plugin environment on the control node, while the module runs on the managed node, so dependencies belong where each one runs (control node / execution environment vs. managed-node Python).
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| ansible-core version | 2.21 is the current version (2026-05 GA, EOL 2027-11); the official ansible.builtin page shows 2.21.6; 2.20 is maintained until 2027-05; 2.19 reached EOL in 2026-11; control node Python 3.12–3.14, managed node Python 3.9–3.14 | ansible.builtin index · Release and maintenance |
| core built-in plugins | callbacks: default, junit, minimal, oneline (deprecated), tree (deprecated); strategies: debug, free, host_pinned, linear; cache: jsonfile, memory | ansible.builtin index |
| ansible.posix | 2.2.2; callbacks cgroup_perf_recap, debug, json, jsonl, profile_roles, profile_tasks, timer | ansible.posix index |
| community.general.yaml callback | Removed in community.general 12.0.0; replaced by the default callback result_format=yaml (core 2.13+) | yaml callback page |
| Playbook debugger | debugger values always/never/on_failed/on_unreachable/on_skipped; enable_task_debugger / ANSIBLE_ENABLE_TASK_DEBUGGER; commands p, task.args, task_vars, u, r, c, q; changing task_vars requires update_task; the debug strategy “may be removed in a future version” | Debugging tasks |
| ssh connection plugin defaults | ssh_args -C -o ControlMaster=auto -o ControlPersist=60s; control_path_dir ~/.ansible/cp; pipelining false; host_key_checking true; transfer_method smart; retries 0; timeout 10 | ansible.builtin.ssh |
| Non-privileged become | Fallback order setfacl → chown → chmod +a → ansible_common_remote_group → world_readable_temp; pipelining does not apply to copy/fetch/template and non-Python modules; error text “Failed to set permissions on the temporary files …” | Privilege escalation |
| Configuration options | forks default 5; gathering default implicit; fact_caching default memory, timeout 86400; keep_remote_files, debug, enable_task_debugger default False; strategy default linear; callbacks_enabled; interpreter_python default auto (auto_silent suppresses warnings); log_verbosity added in 2.17 | Ansible Configuration Settings |
| ARA | PyPI latest 1.8.0; project moved to Codeberg; local SQLite by default; python3 -m ara.setup.callback_plugins; ara-manage runserver; container recordsansible/ara-api; client ARA_API_CLIENT/ARA_API_SERVER; requires Python ≥ 3.10 and the same interpreter as Ansible | PyPI ara · Codeberg README |
| Module/plugin development | AnsibleModule, argument_spec, check mode, documentation format; ansible-test sanity runs in the collection root directory | Developing modules · Sanity tests |
Video verification notes
The following videos were verified on 2026-11-15 via the YouTube oEmbed API to have matching titles and channels: Jeff Geerling “Ansible 101 - Episode 1 - Introduction to Ansible” (goclfp6a2IQ), “Episode 2 - Ad-hoc tasks and Inventory” (7kVfqmGtDL8), “Episode 5 - Playbook handlers, environment vars, and variables” (HU-dkXBCPdU), “Episode 7 - Molecule Testing and Linting and Ansible Galaxy” (FaXVZ60o8L8), “Episode 9 - First 5 min server security with Ansible” (gV_16dU7XjM), “Episode 10 - Ansible Tower and AWX” (iKmY4jEiy_A), “Episode 12 - Real-world Ansible Playbooks” (_QZr4xKhir4), “Episode 13 - Ansible Collections and a Test Plugin” (nyXDR4RG4A8), “Episode 15 - Final LIVE Q&A” (sb5XYD3BLMA); and Fireship “Ansible in 100 Seconds” (xRMPKQweySE). oEmbed does not return duration or date; the Ansible 101 series is a 2020 live recording, so for version details follow this lesson and the official docs. No verified dedicated videos were found for the playbook debugger, pipelining/fact caching, strategies and async, or callbacks and ARA; storyboard scripts are provided instead.
Voice narration notes
The “Audio” page uses the browser's Web Speech API (en-US) to read the lecture script aloud in real time, with English terms pronounced in en-US; the result depends on the voices installed on the system. The generation environment cannot call a TTS service, so no MP3 is embedded; for offline audio, pass the lecture script to a TTS service.
Known limitations
- The commands in this courseware were not actually executed in the generation environment; times, PIDs, hashes, jids, paths and durations in the “expected output” are example values, so follow your own environment.
- The performance experiment maps 30 aliases onto 3 containers, the aliases share the ControlPersist master connection, and RTT is close to 0; the gains from pipelining and forks differ from real multi-host, cross-region environments and are only for comparing relative effects.
- The managed-node containers have no systemd; verify service-management behavior on a VM.
- Some raw error text (such as the specific content of err in a non-privileged become failure, async timeout messages, log line formats, and ARA table columns) varies slightly between versions; this lesson marks them as “example”.
- The times and round-trip counts in the animations and simulators are illustrative values that explain the mechanism; the real round-trip count can be counted yourself using
-vvv | grep -c 'SSH: EXEC'. interpreter_pythonInauto_legacy, the status of legacy values such asgather_subsetand of some global configuration options has not been verified item by item; this lesson only uses play keywords andauto/auto_silent.