Lab: configure a small fleet idempotently with an Ansible playbook
Configure two disposable hosts with an Ansible playbook built from an inventory, modules, a template and a handler, preview changes with check and diff mode, and prove that a second run changes nothing.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start two disposable targets
- Step 2: Write the inventory and test the connection
- Step 3: Write the template and the playbook
- Step 4: Preview the first run with check and diff mode
- Step 5: Run it for real
- Step 6: Prove idempotency with a second run
- Step 7: Change a variable, preview it, then apply it
- Check your understanding
- Apply it
- Review prompt
Lessons of IaC Fundamentals
- Why infrastructure belongs in code: provisioning, configuration and images Concept · 20 min
- Lab: plan, apply and destroy, then extract a reusable module Lab · 40 min
- Remote state, environments and the checks every plan should pass Concept · 25 min
- Reading a plan like a reviewer: drift, import and state refactoring Worked example · 25 min
- Lab: configure a small fleet idempotently with an Ansible playbook Lab · 30 min
- Check: plan review, drift and configuration scenarios Knowledge check · 10 questions
What you will learn
- Configure servers idempotently with an Ansible playbook (inventory, modules, handlers and templates), preview it with check and diff mode, and decide when to bake an image instead.
01. Goal and setup
OpenTofu creates machines; a configuration management tool such as Ansible sets up the software inside them. Ansible is agentless: nothing runs on the managed hosts except SSH and Python. For each task, the control machine (your laptop) by default copies a small Python program, called a module, to the host over SSH, runs it, reads its JSON answer and deletes it.
The property you will test is idempotency: running the same playbook twice leaves the host exactly as one run did. A good module first looks at the host and changes something only if it differs from what you declared. So the first run reports changed, and a second run reports ok for every task and changed=0 in the recap.
You will configure two disposable Debian hosts with nginx: an inventory says which hosts exist, a template renders the nginx site file, and a handler reloads nginx only when that file changes. You will preview each change with check and diff mode before it happens, and see where that preview stops being reliable.
You need: Docker, Python 3.13 or later with ansible-core installed (python3 -m pip install ansible-core; this lab was run with ansible-core 2.22.0, which needs Python 3.13; an older Python gets an older ansible-core, whose messages may differ), ssh-keygen and curl. The two targets are containers that run only an SSH server; nothing else on your machine is changed. Tested with Debian 12 (bookworm) images. Debian 12 is now oldstable, because Debian 13 (trixie) became the stable release in August 2025. A review run of the same playbook on Debian 13 needed no changes; only the package list in step 4 differed. To use it, start the targets with IMAGE=debian:13-slim bash start-targets.sh.
ansible-lab/
├── .ssh-lab/ step 1: lab-only SSH key and known_hosts
├── start-targets.sh step 1: starts node-01 and node-02
├── inventory/
│ ├── hosts.ini step 2: which hosts exist
│ └── group_vars/
│ └── web_fleet.yml step 2: how to connect to them
├── templates/
│ └── nginx.conf.j2 step 3: the nginx site file
└── webserver-setup.yml step 3: the playbook02. Step 1: Start two disposable targets
Create a key that is used only for this lab, then start two containers. Each one installs an SSH server and Python, trusts your lab key for root, and publishes SSH on 127.0.0.1 (ports 2221 and 2222) and HTTP on ports 8081 and 8082. Binding to 127.0.0.1 keeps them unreachable from your network.
#!/usr/bin/env bash
# Two disposable Debian targets (12 by default, or set IMAGE=debian:13-slim):
# SSH on 127.0.0.1:2221/2222, HTTP on :8081/:8082
set -euo pipefail
IMAGE="${IMAGE:-debian:12-slim}"
PREFIX="${PREFIX:-iac-lab}"
PUBKEY="$(cat .ssh-lab/id_ed25519.pub)"
for n in 1 2; do
docker run -d --name "$PREFIX-node-0$n" --hostname "node-0$n" \
-p "127.0.0.1:222$n:22" -p "127.0.0.1:808$n:80" \
-e PUBKEY="$PUBKEY" "$IMAGE" sh -c '
apt-get update -qq &&
apt-get install -y -qq --no-install-recommends \
openssh-server python3 python3-apt >/dev/null &&
mkdir -p /run/sshd /root/.ssh &&
echo "$PUBKEY" > /root/.ssh/authorized_keys &&
chmod 600 /root/.ssh/authorized_keys &&
echo "node ready" && exec /usr/sbin/sshd -D -e'
donemkdir -p ansible-lab/inventory/group_vars ansible-lab/templates && cd ansible-lab
mkdir -m 700 .ssh-lab
ssh-keygen -q -t ed25519 -N '' -C ansible-lab -f .ssh-lab/id_ed25519
# save start-targets.sh here, then:
bash start-targets.sh
sleep 30; docker logs iac-lab-node-01 2>&1 | grep "node ready"4698b0f26a9875c95c0440e83f2da7d7d24b5a052ca962559d66106198b935b1
ace0575213a1f6abcd1afef86b1bd1c4e9901cdb1309f8df5fbf4ee5f55a55d4
node ready03. Step 2: Write the inventory and test the connection
The inventory lists the hosts and puts them in groups. The playbook will target the group web_fleet, not individual addresses, so adding a third server later means adding one line here. Settings that apply to every host in a group go in group_vars/<group>.yml; Ansible loads that folder automatically when it sits next to the inventory file. The SSH options keep the lab host keys in .ssh-lab/known_hosts, so your own ~/.ssh/known_hosts is not touched.
[web_fleet]
node-01 ansible_host=127.0.0.1 ansible_port=2221
node-02 ansible_host=127.0.0.1 ansible_port=2222# Connection settings for every host in the web_fleet group
ansible_user: root
ansible_python_interpreter: /usr/bin/python3
ansible_ssh_private_key_file: .ssh-lab/id_ed25519
ansible_ssh_common_args: >-
-o UserKnownHostsFile=.ssh-lab/known_hosts
-o StrictHostKeyChecking=accept-newansible-inventory -i inventory/hosts.ini --graph
ansible web_fleet -i inventory/hosts.ini -m ansible.builtin.ping@all:
|--@ungrouped:
|--@web_fleet:
| |--node-01
| |--node-02
node-02 | SUCCESS => {
"changed": false,
"ping": "pong"
}
node-01 | SUCCESS => {
"changed": false,
"ping": "pong"
}ping is not a network ping: it logs in over SSH, runs a tiny module with the remote Python and returns pong. Ansible works on up to five hosts at a time by default (the forks setting), which is why their lines can arrive in any order.
04. Step 3: Write the template and the playbook
A template is a file with placeholders. Ansible fills {{ http_port }} and {{ server_name }} with variables (Jinja2 syntax) and writes the result to the host. The extra response header lets you check from outside which version of the file nginx has loaded.
# Managed by Ansible: local edits are overwritten on the next run.
server {
listen {{ http_port }} default_server;
server_name {{ server_name }};
root /var/www/html;
index index.html index.nginx-debian.html;
# Lets you see from outside which version of this file nginx loaded
add_header X-Config-Server-Name "{{ server_name }}" always;
location / {
try_files $uri $uri/ =404;
}
}---
- name: Configure web fleet
hosts: web_fleet
become: true
vars:
http_port: 80
server_name: "app.internal.example"
tasks:
- name: Ensure nginx web server is installed
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
install_recommends: false
- name: Template virtualhost configuration file
ansible.builtin.template:
src: templates/nginx.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: "0644"
notify: Reload nginx
- name: Check nginx configuration syntax
ansible.builtin.command: nginx -t
changed_when: false
- name: Ensure nginx service is enabled and running
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloadedEach task declares a result, not a command. apt with state: present installs nginx only if it is missing, and cache_valid_time: 3600 skips refreshing the package lists when they are less than an hour old. template compares the rendered text with the file on the host and writes only if they differ. service with state: started starts nginx only if it is stopped.
The nginx -t task is different. command cannot know what an arbitrary program does, so it would report changed on every run; changed_when: false tells Ansible that this check never changes the host. If the rendered file is broken, nginx -t fails, Ansible stops working on that host, and its pending handler does not reload nginx with the bad file.
05. Step 4: Preview the first run with check and diff mode
--check runs every task in a simulation: modules inspect the host and report what they would change, but change nothing. --diff adds a before-and-after view of files. Try both on the fresh hosts before the real run.
ansible-playbook -i inventory/hosts.ini webserver-setup.yml --check --diffTASK [Ensure nginx web server is installed] ************************************
The following NEW packages will be installed:
iproute2 libbpf1 libcap2-bin libelf1 libmnl0 libxtables12 nginx nginx-common
0 upgraded, 8 newly installed, 0 to remove and 0 not upgraded.
changed: [node-02]
…
TASK [Template virtualhost configuration file] *********************************
--- before
+++ after: …/.ansible/tmp/ansible-local-…/nginx.conf.j2
@@ -0,0 +1,14 @@
+# Managed by Ansible: local edits are overwritten on the next run.
+server {
+ listen 80 default_server;
+ server_name app.internal.example;
…
changed: [node-01]
…
TASK [Check nginx configuration syntax] ****************************************
skipping: [node-02]
skipping: [node-01]
TASK [Ensure nginx service is enabled and running] *****************************
[ERROR]: Task failed: Module failed: Could not find the requested service nginx: host
…
fatal: [node-01]: FAILED! => {"changed": false,
"msg": "Could not find the requested service nginx: host"}
…
PLAY RECAP *********************************************************************
node-01 : ok=3 changed=2 unreachable=0 failed=1
skipped=1 rescued=0 ignored=0
node-02 : ok=3 changed=2 unreachable=0 failed=1
skipped=1 rescued=0 ignored=0The preview is useful (the diff shows exactly which file would appear, with which content) but it also failed, and nothing is wrong with the playbook. Check mode only predicts, and that has three limits you just saw or should expect:
- Tasks that depend on an earlier change. The
apttask said nginx would be installed, but it was not, so theservicetask found no nginx service to start. commandandshelltasks are skipped, because Ansible cannot predict what an arbitrary program does. Herenginx -tdid not run, so check mode did not test the new configuration. A module can declare check-mode support for some options only:commandwithcreates:orremoves:can predict its result.- Tasks that branch on an earlier result. A task whose
when:reads aregistered result from a skipped or simulated task may decide differently than in a real run.
So --check --diff is most trustworthy on hosts that are already configured, where you want to see what a change would do. For a brand-new host, the real run in a disposable environment is the test.
06. Step 5: Run it for real
ansible-playbook -i inventory/hosts.ini webserver-setup.yml
curl -sI http://127.0.0.1:8081/ | grep -i x-configPLAY [Configure web fleet] *****************************************************
TASK [Gathering Facts] *********************************************************
ok: [node-02]
ok: [node-01]
TASK [Ensure nginx web server is installed] ************************************
changed: [node-02]
changed: [node-01]
TASK [Template virtualhost configuration file] *********************************
changed: [node-01]
changed: [node-02]
TASK [Check nginx configuration syntax] ****************************************
ok: [node-01]
ok: [node-02]
TASK [Ensure nginx service is enabled and running] *****************************
changed: [node-02]
changed: [node-01]
RUNNING HANDLER [Reload nginx] *************************************************
changed: [node-01]
changed: [node-02]
PLAY RECAP *********************************************************************
node-01 : ok=6 changed=4 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
node-02 : ok=6 changed=4 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
X-Config-Server-Name: app.internal.exampleGathering Facts is an automatic first task that collects details about each host (OS, addresses) into variables. The service task reports changed here because Debian container images block services from starting during package installation; on a normal Debian or Ubuntu VM the package usually starts nginx itself, and that task would report ok. The handler ran because the template changed.
07. Step 6: Prove idempotency with a second run
ansible-playbook -i inventory/hosts.ini webserver-setup.yml | tail -4
ansible-playbook -i inventory/hosts.ini webserver-setup.yml --check --diff | tail -4PLAY RECAP *********************************************************************
node-01 : ok=5 changed=0 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
node-02 : ok=5 changed=0 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
PLAY RECAP *********************************************************************
node-01 : ok=4 changed=0 unreachable=0 failed=0
skipped=1 rescued=0 ignored=0
node-02 : ok=4 changed=0 unreachable=0 failed=0
skipped=1 rescued=0 ignored=0The second real run reports changed=0: every module inspected the host and found it already as declared, and because nothing notified the handler, nginx was not reloaded (ok=5, one fewer than before). The check-mode run after it also shows changed=0 and prints no diff, because no file would change; its one skipped task is nginx -t. A recap with changed=0 on an unchanged host is the test that a playbook is idempotent. A task that reports changed every time, such as a shell command without changed_when or creates, fails that test.
08. Step 7: Change a variable, preview it, then apply it
Change server_name and preview the effect on one host. Diff output gets long on many hosts, so --limit restricts the run to node-01.
sed -i "s/app.internal.example/shop.internal.example/" webserver-setup.yml
ansible-playbook -i inventory/hosts.ini webserver-setup.yml --check --diff \
--limit node-01
curl -sI http://127.0.0.1:8081/ | grep -i x-configTASK [Template virtualhost configuration file] *********************************
--- before: /etc/nginx/sites-available/default
+++ after: …/.ansible/tmp/ansible-local-…/nginx.conf.j2
@@ -1,12 +1,12 @@
# Managed by Ansible: local edits are overwritten on the next run.
server {
listen 80 default_server;
- server_name app.internal.example;
+ server_name shop.internal.example;
root /var/www/html;
index index.html index.nginx-debian.html;
# Lets you see from outside which version of this file nginx loaded
- add_header X-Config-Server-Name "app.internal.example" always;
+ add_header X-Config-Server-Name "shop.internal.example" always;
location / {
try_files $uri $uri/ =404;
changed: [node-01]
TASK [Check nginx configuration syntax] ****************************************
skipping: [node-01]
TASK [Ensure nginx service is enabled and running] *****************************
ok: [node-01]
RUNNING HANDLER [Reload nginx] *************************************************
changed: [node-01]
PLAY RECAP *********************************************************************
node-01 : ok=5 changed=2 unreachable=0 failed=0
skipped=1 rescued=0 ignored=0
X-Config-Server-Name: app.internal.exampleThis is the review you want before touching a running fleet: exactly one task would change, the diff shows the two lines, and the handler would reload nginx. curl still returns the old name, which proves check mode changed nothing. Now apply it to both hosts:
ansible-playbook -i inventory/hosts.ini webserver-setup.yml | tail -4
curl -sI http://127.0.0.1:8082/ | grep -i x-configPLAY RECAP *********************************************************************
node-01 : ok=6 changed=2 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
node-02 : ok=6 changed=2 unreachable=0 failed=0
skipped=0 rescued=0 ignored=0
X-Config-Server-Name: shop.internal.exampleWhen you are done, remove the targets with docker rm -f iac-lab-node-01 iac-lab-node-02 and delete the .ssh-lab folder.
Configuring at runtime is not always the right place for this work. If new VMs are launched by autoscaling and each had to run a ten-minute playbook before it could serve traffic, you would bake an image instead: run the same playbook once in an image build (for example with Packer), and boot new VMs from that image. Keep the runtime playbook for what differs per host or changes often, as lesson 1 explains.
09. Check your understanding
10. Apply it
Take one setup script your team runs by hand and turn it into a playbook. Then hold it to these rules:
- Prefer modules that check state (
apt,template,service,lineinfile) overcommandandshell; when you need a command, addchanged_whenorcreates. - Restart or reload services from handlers, so they react only to real changes.
- Run it twice against a disposable host and require
changed=0on the second run, for example in a CI job with Molecule, the Ansible testing tool. - Before changing a running fleet, run
--check --diff --limiton one host and read the diff.
11. Review prompt
Without looking back, explain what makes a task idempotent and how a recap shows it. Describe when a handler runs and when it does not. Name two reasons a --check run can differ from a real run, and say when you would bake an image instead of configuring hosts at boot.
References
- Ansible docs: Validating tasks: check mode and diff mode
- Ansible docs: ansible.builtin.command (check mode support)
- Ansible docs: ansible.builtin.apt module
- Ansible docs source (GitHub): Handlers: running operations on change
- Ansible docs source (GitHub): How to build your inventory
- Ansible docs source (GitHub): Error handling in playbooks
- Molecule: testing framework for Ansible collections, playbooks and roles (GitHub)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.