HostiServer
2026-11-17 11:20
Ansible Playbooks: Tasks, Handlers, Loops, and Tags
📚 "Ansible" series, part 2 of 10:
- Ansible: Architecture, Installation, Inventory, and Your First Ad-Hoc Commands
- Ansible Playbooks: Tasks, Modules, Handlers, Loops, and Tags ← you are here
- Ansible Variables and Jinja2 Templates: host_vars, group_vars, Precedence
- Ansible in Practice: nginx, Firewall, SSH Keys, and Users on a Real VPS
- Ansible Roles: Structure, Includes/Imports, and Best Practices
- Ansible Galaxy and Collections: requirements.yml and Installation
- Ansible Vault: Secrets, vault-id, and Playbook Integration
- Ansible at Scale: forks, serial, pipelining, and SSH Multiplexing for 100+ Nodes
- Dynamic Inventory in Ansible: Plugins for Hetzner, AWS, and GCP
- Ansible + CI/CD: ansible-lint and Auto-Deploy via Forgejo and GitHub Actions
Ansible Playbooks: Tasks, Modules, Handlers, Loops, and Tags
In the first article of the series, we installed Ansible, described our servers in the inventory, and ran our first ad-hoc commands. This technique works great for one-off actions: checking reachability, looking at uptime, restarting a service. But the moment you catch yourself typing the same sequence of commands for the third time, ad-hoc starts getting in the way: the sequence isn't saved anywhere, conditions ("restart the service only if the config changed") can't be expressed, and a colleague won't see what exactly you did on the servers.
A playbook solves all three problems. It's a text file where you describe what should be on the servers, one you can keep in git, review in a pull request, and run as many times as needed. In this article we'll break down everything a playbook consists of: plays, tasks, modules, idempotence, handlers, variables, loops, and tags. By the end you'll have a working playbook that installs and configures nginx on every web server in the inventory.
1.1 Ad-Hoc or Playbook
| Criterion | Ad-Hoc | Playbook |
|---|---|---|
| Purpose | One-off action | Repeatable description of state |
| Where it's stored | Only in shell history | In a file that lives in git |
| Multiple steps and conditions | One module per run, no logic | A sequence of tasks, when, loops, handlers |
| Checking before running | Limited | --check and --diff for the whole scenario |
| Readability for the team | You need to know what was actually run | The description reads like documentation |
1.2 What a Playbook and a Play Are
A playbook is a YAML file whose top level is a list of plays. Each play answers two questions: "on which hosts?" (the hosts field, which draws on groups from the inventory) and "what should be done on them?" (the list of tasks). A single playbook can contain several plays: for example, the first one configures the web servers, the second one the databases.
Three main advantages of this approach:
- Versioning. The file lives in git alongside the inventory, and any infrastructure change is visible in the commit history.
- Idempotence. A playbook describes the desired state, so running it again doesn't break anything.
- Readability. YAML with clearly named tasks lets a colleague read the scenario without help from the author.
ℹ️ What you'll need: a working Ansible setup, an inventory with a webservers group, and SSH access with sudo to those servers. We set all of this up in part 1. The examples below are written for Debian/Ubuntu; where RHEL-family systems need changes, we call that out separately.
2. Anatomy of a Playbook
2.1 A Minimal Example
Let's start with the shortest useful playbook: it checks connectivity to the web servers and shows which OS they're running.
---
- name: Check web servers
hosts: webservers
tasks:
- name: Ping servers
ansible.builtin.ping:
- name: Show OS family
ansible.builtin.debug:
msg: "{{ inventory_hostname }} is running {{ ansible_facts['os_family'] }}"
Save it as check.yml and run:
ansible-playbook check.yml
2.2 Play Fields
name— a human-readable name for the play. Not strictly required, but it's what appears in the output (PLAY [...]), so without it the run log is hard to read.hosts— which hosts to run on: a group, a host, or any pattern, as covered in part 1.become— whether to escalate privileges via sudo. Set at the play level, it applies to all of its tasks.vars— the play's variables (more on this in section 6).tasks— the list of actions, executed in order.handlers— actions that only run when a signal is received from tasks (section 5).
2.3 Execution Order
Ansible executes a play from top to bottom: first it gathers facts about the host (the Gathering Facts task, which appears in the output automatically), then it works through the tasks in the order they're written, and only afterward runs any handlers that were notified. Within a single task, the action runs on all hosts matched by hosts, and Ansible moves to the next task once the previous one has finished on all hosts (the number of hosts running at once is controlled by the forks parameter from part 1). If a task fails on some host, that host is excluded from the rest of the play while the others continue.
⚠️ Common YAML pitfalls. Indentation must use spaces only (usually two), since tabs break the file. For boolean values, use true and false rather than yes and no. Always quote a string that starts with {{: msg: "{{ var }}", otherwise YAML will read it as a data structure and throw a parse error.
3. Tasks and Modules
3.1 A Task Is One Module Call
A task is a single action: you pick a module and set its parameters. The module, just as in ad-hoc, does all the work; the only difference is that the call is written into a file, has a name, and can have extra logic wrapped around it (conditions, loops, tags, handler signals).
- name: Install nginx
ansible.builtin.package:
name: nginx
state: present
3.2 The Most Common Built-In Modules
| Module | What It's For | Key Parameters |
|---|---|---|
ansible.builtin.package, apt, dnf |
Packages | name, state (present, absent, latest) |
ansible.builtin.copy, template |
Files: copied as-is or with variable substitution (Jinja2 templates — covered in part 3) | src or content, dest, mode, owner |
ansible.builtin.service |
Services | name, state (started, stopped, restarted, reloaded), enabled |
ansible.builtin.user, group |
Users and groups | name, state, shell, groups, append |
ansible.builtin.file |
Directories, permissions, ownership, symlinks | path, state (directory, absent, link), mode, owner |
ansible.builtin.command, shell |
An arbitrary command (last resort, when there's no dedicated module) | the command itself; creates, removes |
The package module is a "wrapper" that picks the system's package manager (apt, dnf, and so on) for you. But it doesn't remove every difference: package names can differ between distributions (for example, the Apache web server is called apache2 on Debian and httpd on RHEL). For nginx the name is the same everywhere, so package works fine here. For differing names, use a condition on the ansible_facts['os_family'] fact (section 6) or the specific apt and dnf modules.
3.3 FQCN: Fully Qualified Module Names
FQCN (Fully Qualified Collection Name) is the full name of a module including its collection: ansible.builtin.copy instead of just copy. Built-in modules work fine under their short names too, so why write the longer form?
- No ambiguity. Collections you install later (part 6) may contain modules with the same short names, and Ansible could then pick the wrong one. The full name removes that risk.
- Clarity. From
community.general.ufworansible.posix.authorized_keyit's immediately clear which collection the module belongs to and which one you need installed. - Tooling. The
ansible-lintlinter, which we'll set up in part 10, has anfqcnrule that requires full names.
Rule of thumb: always write FQCN in new playbooks. We do the same throughout this series.
3.4 changed_when and failed_when
The command and shell modules don't know whether a command changed the system's state, so they report "changed" every time (we already saw this in part 1). Two keywords let you define for yourself what counts as a change and what counts as a failure:
- name: Validate nginx config
ansible.builtin.command: nginx -t
changed_when: false
- name: Check root disk usage
ansible.builtin.shell: df --output=pcent / | tail -1 | tr -dc '0-9'
register: disk
changed_when: false
failed_when: disk.stdout | int > 90
The first task only validates the configuration and doesn't change anything, so changed_when: false keeps the output clean ("ok" instead of "changed"). The second counts how full the root partition is and declares it a failure once disk usage exceeds 90%. The expression in changed_when and failed_when, just as in when, is already a Jinja2 expression, so you don't need to wrap it in {{ }}.
4. Idempotence in Practice
4.1 What It Means
Idempotence is the guarantee that running something again won't change the system if it's already in the desired state. A module checks the current state, compares it to the desired one, and acts only when needed. The practical consequence: a playbook can safely be run again after a failure, after a manual change, or simply "just to be sure."
4.2 Which Modules Are Idempotent
- Idempotent by nature:
package/apt/dnf(package already installed — do nothing),service(service already running — do nothing),file,copy, andtemplate(file already has the desired content and permissions — do nothing),user. - Not idempotent:
commandandshell. Ansible doesn't know what your command does, so it can't tell whether it's worth running again.
4.3 Making command and shell Safer
There are three tools for this:
creates— don't run the command if the specified file already exists;removes— don't run the command if the specified file no longer exists;changed_when: false— for commands that only read state.
- name: Initialize app database (only once)
ansible.builtin.command: /opt/app/bin/init-db
args:
creates: /var/lib/app/.initialized
If this command creates the marker file /var/lib/app/.initialized, future runs will skip it. But the main rule still stands: if a dedicated module exists for the job, use it instead of command.
4.4 Checking Without Changing: --check and --diff
The --check flag runs the playbook in "dry run" mode: modules that support it report what they would change but change nothing. The --diff flag adds a file diff on top of that: you see the lines that would appear or disappear in the configuration. Together they answer the question "what will happen if I run this?" before anything actually happens.
ansible-playbook site.yml --check --diff
⚠️ A dry run isn't absolute. In check mode, command and shell are usually skipped, and subsequent tasks may depend on results from the ones that were skipped (for example, a service that's "not yet installed" in the dry run). So --check is a useful hint, not a guarantee. For critical changes, run against one server first (--limit, section 10).
5. Handlers: an Action Only When Something Changed
5.1 Why They're Needed
A classic example: you've updated the nginx configuration and want the service to pick it up. Restarting nginx every single time, even when the config hasn't changed, is wasteful and even harmful: it's an unnecessary connection interruption. A handler solves this: it's a task that only runs when some other task reported a change.
5.2 notify and Handlers
A handler is declared in a play's handlers section and triggered by the notify keyword in a task:
tasks:
- name: Deploy nginx app config
ansible.builtin.copy:
src: files/app.conf
dest: /etc/nginx/conf.d/app.conf
mode: "0644"
notify: Reload nginx
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
If the file on the server already matches the source, copy returns "ok", no signal is sent, and nginx is left alone. If the file changed, "changed" is returned, the handler is queued, and it runs.
5.3 When Exactly Handlers Run
- Once. No matter how many tasks notify the same handler, it runs only once per host.
- At the end. Notified handlers run after all of the play's tasks have finished (more precisely, after the
pre_tasks,roles/tasks, andpost_taskssections). - In declared order. Handlers run in the order they're written in the
handlerssection, not in the order they were notified. - A shared namespace. All handlers in a play, including ones that come from roles, share a single namespace. If two handlers have the same name, the one loaded last wins. So give handlers unique, descriptive names.
5.4 flush_handlers: Running Earlier
Sometimes a later task depends on a handler having already run. For example, after a configuration change you want to verify that nginx is responding on the new port. If you wait until the end of the play, the check will come before the reload and fail. The special meta: flush_handlers task forces every handler notified so far to run immediately:
- name: Apply pending handlers now
ansible.builtin.meta: flush_handlers
After this, handlers can be notified and run again later in the same play.
5.5 Nuances Worth Knowing
- Handlers ignore tags. If you ran with
--tags configureand a handler doesn't have that tag, it still runs once it's been notified (section 8). - A failure cancels the notification. If some task on a host fails, that host's notified handlers won't run by default. That means the configuration has already been changed on disk, but the service hasn't reloaded it yet. After fixing the failure, a rerun won't necessarily produce "changed" again (the file is already updated), so the handler won't fire. If you need a guarantee it will run, use the
force_handlers: truekeyword on the play or the--force-handlersflag at runtime. - Multiple handlers for one event. With
listen, a handler subscribes to a "topic," and a single notification on that topic triggers every handler subscribed to it, regardless of their names. The topic can't be set from a variable. - Variables in names. Don't substitute variables into handler names: if the variable is undefined, the play fails outright. Pass variables to the handler's parameters instead.
6. Variables in Tasks: an Introduction
The full variable system (host_vars, group_vars, precedence, templates) is covered in part 3. Here we take just the minimum needed to make a playbook practical.
6.1 vars and {{ }} Substitution
Simple values can be set directly in a play's vars section, then used anywhere via Jinja2 substitution:
- name: Configure nginx on the web servers
hosts: webservers
become: true
vars:
app_port: 8080
tasks:
- name: Check that app answers
ansible.builtin.uri:
url: "http://127.0.0.1:{{ app_port }}/"
return_content: true
Always quote a value that starts with {{ }}, and when a variable is part of a larger string, as in the example above, the whole string needs quotes too.
6.2 register: Saving a Task's Result
The register keyword captures everything a module returned (exit code, output, status, response body) into a variable you can work with later:
- name: Check that app answers
ansible.builtin.uri:
url: "http://127.0.0.1:{{ app_port }}/"
return_content: true
register: app_check
- name: Show app response
ansible.builtin.debug:
msg: "Response: {{ app_check.content | trim }}"
The easiest way to see exactly which fields a registered variable has is to run with -v: Ansible will print the full result of the task.
6.3 when: Conditional Execution
The when keyword runs a task only if the condition is true. The condition is written as a plain expression, without curly braces:
- name: Install Apache on Debian family
ansible.builtin.apt:
name: apache2
state: present
when: ansible_facts['os_family'] == "Debian"
- name: Install Apache on RedHat family
ansible.builtin.dnf:
name: httpd
state: present
when: ansible_facts['os_family'] == "RedHat"
Ansible gathers system facts (including os_family) automatically at the start of the play. The condition is evaluated separately for each host, so a single playbook can behave differently on Debian and on AlmaLinux. Multiple conditions can be combined with and/or, or written as a list (in which case they're combined with "and").
⚠️ Don't wrap conditions in {{ }}. Writing when: "{{ var }}" is a common mistake: when already evaluates a Jinja2 expression, and the extra braces produce a warning or unexpected behavior.
7. Loops: Repeating a Task
7.1 loop: Iterating Over a List
When the same action needs to run for several values, use loop instead of duplicating tasks. The current element on each iteration is available as the item variable:
- name: Create service users
ansible.builtin.user:
name: "{{ item.name }}"
comment: "{{ item.comment }}"
shell: /bin/bash
loop:
- { name: alice, comment: "Alice, backend" }
- { name: bob, comment: "Bob, ops" }
loop_control:
label: "{{ item.name }}"
For a simple list of values the syntax is even shorter: loop: [git, curl, htop] with name: "{{ item }}". But note: the package, apt, and dnf modules accept a list directly in the name parameter. Installing several packages in one task is faster than looping: the package manager is invoked only once.
- name: Install base packages
ansible.builtin.package:
name:
- git
- curl
- htop
state: present
7.2 loop_control: Controlling the Loop
| Parameter | What It Does |
|---|---|
label |
Shortens the output: instead of the full dictionary for each element, shows a chosen field (for example, item.name). This is purely about readability: it doesn't hide sensitive data — that's what no_log: true is for |
pause |
Pause in seconds between iterations |
index_var |
Name of the variable that holds the iteration's index (starting at zero) |
loop_var |
Renames item. Needed when a loop is nested inside another loop (for example, via include_tasks), so the inner one doesn't overwrite the outer item |
extended |
Adds an ansible_loop variable with the fields first, last, index, previtem, nextitem |
7.3 loop or with_items
Loops used to be written with with_items, with_list, and other with_* forms. Ansible's documentation recommends the modern loop keyword for most cases, though the with_* forms haven't formally been deprecated: they still work, and plenty of existing playbooks use them. There's one difference worth knowing when rewriting: with_items automatically "flattens" nested lists by one level, while loop doesn't, so migrating sometimes needs the flatten(1) filter. The with_* forms remain justified when you need a lookup plugin inside a loop (for example, with_fileglob).
7.4 Complex Structures: subelements
When data is nested (each user has their own list of SSH keys), the old with_subelements form is replaced by loop with the subelements filter. Example: distributing each user's keys into their authorized_keys:
vars:
users:
- name: alice
ssh_keys:
- "ssh-ed25519 AAAA...alice-laptop"
- "ssh-ed25519 AAAA...alice-phone"
- name: bob
ssh_keys:
- "ssh-ed25519 AAAA...bob-laptop"
tasks:
- name: Add SSH keys for users
ansible.posix.authorized_key:
user: "{{ item.0.name }}"
key: "{{ item.1 }}"
loop: "{{ users | subelements('ssh_keys') }}"
loop_control:
label: "{{ item.0.name }}"
For each "user + key" pair, item.0 is the user's record and item.1 is one of their keys. The ansible.posix.authorized_key module belongs to the ansible.posix collection, which is included in the full ansible package we installed in part 1; we'll cover managing collections in part 6.
7.5 Loops with register and when
- If a looped task has
register, the variable holds aresultslist with one entry per iteration. The overallchangedandfailedare true if at least one iteration changed or failed. - A
whencondition on a looped task is evaluated separately for each element, so it's convenient for filtering:when: item.name != "bob".
8. Tags: Running Just Part of a Playbook
8.1 Why They're Needed
Once a playbook grows to a hundred tasks, running it in full for a single configuration change takes too long. Tags let you mark tasks and run only the ones you need. It's important to understand the two-step nature of this: the tags keyword only marks tasks, while it's a flag at runtime that selects or skips them.
8.2 Where to Assign Tags
- On a task:
tags: configureor a list,tags: [configure, nginx]. - On a play: the tag applies to every task in the play, including automatic fact gathering and tasks from roles.
- On a block, a role, a static import: the tag is inherited by every nested task.
- Dynamic includes (
include_tasks,include_role): the tag applies only to the include itself, not to the file's contents. The documentation separately warns that mixing import and include in the same playbook can produce hard-to-diagnose errors. - Handlers: tags are ignored.
8.3 Running With Tags
# Only tasks tagged configure
ansible-playbook site.yml --tags configure
# Everything except tasks tagged install
ansible-playbook site.yml --skip-tags install
# Several tags, comma-separated
ansible-playbook site.yml --tags "install,service"
# Which tags exist and exactly what will run
ansible-playbook site.yml --list-tags
ansible-playbook site.yml --tags configure --list-tasks
If you set both --tags and --skip-tags, the skip takes priority. The --list-tasks flag lets you see what will run before actually running it. It doesn't show tasks inside dynamic includes or roles.
8.4 Reserved Tags
| Tag | Behavior |
|---|---|
always |
The task always runs, even when you specified other tags, unless it's explicitly skipped with --skip-tags always |
never |
The task is skipped unless explicitly requested (--tags never or another tag on that task). Good for dangerous or diagnostic actions that shouldn't run by accident |
tagged, untagged, all |
Only work on the command line: --tags tagged runs tasks that have at least one tag, --tags untagged runs ones with none, --tags all runs everything (the default, except never) |
- name: Dump all facts for debugging
ansible.builtin.debug:
var: ansible_facts
tags: [never, debug]
This task won't run during a normal run, but will show up when you run the playbook with --tags debug.
⚠️ Tags and dependencies between tasks. Filtering by tag skips everything that doesn't match — including a task that prepares a variable for a later one. If you run only --tags verify while the app_check variable is created by a different task via register, you'll get an "undefined variable" error. Give dependent tasks the same tag. Fact gathering is tagged always by default, but can still be skipped if you explicitly skip it or tag the entire play.
8.5 In Practice: Tags for Groups of Tasks
A working scheme for most playbooks: install for installing packages, configure for files and configuration, service for managing services, verify for checks. Then a configuration-only change can be run with --tags configure and takes seconds instead of minutes.
9. File Structure and Best Practices
9.1 A Combined Example: site.yml
Let's put everything we've covered into one playbook that installs nginx, deploys a simple site on port 8080, and checks that it responds. Create this structure:
ansible-project/
├── ansible.cfg
├── inventory/
│ └── hosts.ini
├── files/
│ └── app.conf
└── site.yml
The files/app.conf file:
server {
listen 8080;
server_name _;
root /var/www/app;
index index.html;
}
The site.yml file:
---
- name: Configure nginx on the web servers
hosts: webservers
become: true
vars:
app_port: 8080
tasks:
- name: Install nginx
ansible.builtin.package:
name: nginx
state: present
tags: install
- name: Create web root
ansible.builtin.file:
path: /var/www/app
state: directory
owner: root
group: root
mode: "0755"
tags: configure
- name: Deploy index page
ansible.builtin.copy:
content: "Hello from Ansible\n"
dest: /var/www/app/index.html
mode: "0644"
tags: configure
- name: Deploy nginx app config
ansible.builtin.copy:
src: files/app.conf
dest: /etc/nginx/conf.d/app.conf
mode: "0644"
notify: Reload nginx
tags: configure
- name: Validate nginx config
ansible.builtin.command: nginx -t
changed_when: false
tags: configure
- name: Ensure nginx is started and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true
tags: service
- name: Apply pending handlers now
ansible.builtin.meta: flush_handlers
- name: Check that app answers
ansible.builtin.uri:
url: "http://127.0.0.1:{{ app_port }}/"
return_content: true
register: app_check
tags: verify
- name: Show app response
ansible.builtin.debug:
msg: "Response: {{ app_check.content | trim }}"
tags: verify
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
Notice a few decisions here. Before reloading nginx, we validate the configuration with nginx -t: if there's a mistake in app.conf, the play stops before it reaches the running service. The flush_handlers task is placed before the check, so nginx has time to reload the config. File modes ("0644") are written in quotes, so they're unambiguously read as a string rather than a number. The port 8080 is currently duplicated in two places: in the app_port variable and in app.conf. We'll fix this shortcoming in part 3, once the config becomes a template and the port is pulled from a single variable.
Port 8080 is only reachable locally until you open it up in the firewall yourself. We'll automate firewall configuration in part 4; for now the Check that app answers task is enough, since it queries 127.0.0.1 from the server itself.
9.2 What a Run Looks Like
A first run on a "clean" Debian/Ubuntu box (output trimmed, the numbers may vary by system):
$ ansible-playbook site.yml
PLAY [Configure nginx on the web servers] **************
TASK [Gathering Facts] *********************************
ok: [web1]
ok: [web2]
TASK [Install nginx] ***********************************
changed: [web1]
changed: [web2]
TASK [Create web root] *********************************
changed: [web1]
changed: [web2]
...
RUNNING HANDLER [Reload nginx] *************************
changed: [web1]
changed: [web2]
TASK [Show app response] *******************************
ok: [web1] => {
"msg": "Response: Hello from Ansible"
}
PLAY RECAP *********************************************
web1 : ok=10 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=10 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
A second run shows idempotence in action:
PLAY RECAP *********************************************
web1 : ok=9 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=9 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Zero changes means the servers are already in the desired state. The handler didn't run, because no task reported a change. On Debian and Ubuntu, nginx starts right after installation, so the Ensure nginx is started and enabled task shows "ok"; on RHEL-family systems it will show "changed" on the first run.
9.3 One Playbook or Several
A single site.yml is enough for a small project. As plays for different groups of servers grow, they're split into separate files and assembled into a "master" playbook via import_playbook:
---
- ansible.builtin.import_playbook: webservers.yml
- ansible.builtin.import_playbook: databases.yml
This way, ansible-playbook site.yml configures the whole fleet, while ansible-playbook webservers.yml handles just the web servers. Once logic starts appearing in reusable chunks (installing nginx for different projects), it's time for roles, which we'll cover in part 5.
9.4 Rules That Save Time
- Name every task as "verb + object + context":
Install nginx,Deploy nginx app config. Names end up in the output, and that's how you track down a problem. - Don't use
shellandcommandwhen a module exists. A dedicated module is idempotent, checkable with--check, and gives a clear result. - Write full module names (FQCN).
- Keep playbooks in git alongside the inventory and
ansible.cfg. Change infrastructure only through changes to the repository. - Write file modes as quoted strings:
"0644". - Don't embed secrets in a playbook in plain text. That's what Ansible Vault is for (part 7).
10. Running and Troubleshooting
10.1 Before Running: Syntax and Dry Run
ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --check --diff
The first command checks that the YAML and structure are correct and runs nothing. The second shows what changes would be made, along with a diff of any files.
10.2 Running Against Part of the Fleet: --limit
ansible-playbook site.yml --limit web1
ansible-playbook site.yml --limit 'webservers:!web2'
The --limit (-l) flag narrows the host list to the given pattern (the same syntax as in part 1). This is the basis of a safe rollout: one server first, confirm it's fine, then the rest.
10.3 Recovering From a Failure: --start-at-task
ansible-playbook site.yml --start-at-task "Deploy nginx app config"
The playbook will start from the task with that exact name (the name must match exactly, so once again: clear task names pay off). Keep dependencies in mind: if skipped tasks registered variables, later tasks won't see them. And since a playbook is idempotent, it's often simpler to just run it again in full.
10.4 Verbosity Levels
-v— shows task results (useful forregister);-vv— adds task input data;-vvv— adds connection details (SSH): the first thing worth enabling forUNREACHABLE;-vvvv— even more detail, including the SSH commands themselves.
10.5 Run Cheat Sheet
| Command | What It Does |
|---|---|
ansible-playbook site.yml |
Runs the playbook in full |
--syntax-check |
Checks syntax without running anything |
--check --diff |
A dry run showing a diff of the files |
--limit web1 |
Restricts the run to the given hosts or groups |
--tags / --skip-tags |
Runs or skips tasks by tag |
--list-tasks / --list-tags |
Shows tasks or tags without running anything |
--start-at-task "name" |
Starts at the given task |
--force-handlers |
Runs notified handlers even after a failure |
-v … -vvvv |
Increases output verbosity |
Summary and What's Next
What We Covered
- A playbook is a YAML file containing a list of plays; a play combines
hostswith a list of tasks, executed top to bottom. - A task calls a module; full names (FQCN) avoid ambiguity, while
changed_whenandfailed_whenlet you define change and failure yourself. - Idempotence is the main advantage:
package,service,file,copyare safe to run again, whilecommand/shellneedcreates,removes, orchanged_when. - Handlers run once at the end of a play, only when a task reported a change;
flush_handlersruns them earlier. register,when, andloopgive a playbook flexibility, while tags let you run only the part you need.- Before a real run,
--syntax-check,--check --diff, and--limitare all worth using.
What's Next in the Series
In our example, port 8080 is currently repeated in two places, and the list of servers, users, and packages is "hardcoded" into the playbook itself. The next article fixes this: we'll cover variables at the host_vars and group_vars levels, defaults, precedence rules, and Jinja2 templates, which let a single configuration file be generated differently for each server. After that, in part 4, we'll apply all of it to a real VPS: nginx, firewall, SSH keys, and users.
🚀 A Playground for Your Playbooks
The best way to get comfortable with playbooks is to run them against real servers and not be afraid of mistakes. Spin up a few inexpensive VPS instances, one as the control node and the rest as targets, and sharpen your scenarios on a safe "playground" before touching production. Hostiserver has resources for this at any scale.
🖥️ Dedicated Servers
- From $90/mo, full control over the hardware for heavy workloads
- No resource-sharing neighbors: predictable performance for databases and build nodes
- 24/7 support: we'll help with networking and SSH access between your servers
💻 Cloud (VPS) Hosting
- From $19.95/mo, KVM isolation, dedicated vCPU and RAM
- Full root access: a playbook gets all the permissions it needs, no workarounds
- Several identical VPS instances: convenient for testing scenarios against groups of servers
- Easy to scale: add a server to the inventory, and it's under Ansible's control
💬 Not sure which option you need?
💬 Message us — we'll help you choose!
Frequently Asked Questions
- How is a playbook different from an ad-hoc command?
An ad-hoc command runs a single action and isn't saved anywhere. A playbook is a file with a sequence of tasks, conditions, loops, and handlers, which is kept in git and runs repeatably and idempotently. Ad-hoc is convenient for one-off checks; a playbook is for anything you intend to repeat.
- Why didn't my handler fire?
There are a few common causes. First, no task returned "changed," so no notification was sent (check that you're looking at the right task). Second, some task on that host failed: by default, notified handlers don't run after a failure, and you can fix that with
force_handlers: trueor--force-handlers. Third, the name innotifydoesn't exactly match the handler's name — check case and spacing. Finally, remember that handlers run at the end of the play, so later tasks see the "old" state unless you usedflush_handlers.
- Which is better: loop or with_items?
Ansible's documentation recommends
loopfor new playbooks. Thewith_*forms haven't been deprecated and keep working, so you'll still run into them in other people's code. The main difference is thatwith_items"flattens" nested lists by one level whileloopdoesn't, so migrating sometimes needs theflatten(1)filter. And for installing several packages, you don't need a loop at all — just pass a list to the module'snameparameter.
- Do I have to write fully qualified module names (FQCN)?
For built-in modules, short names work fine, so technically it's not required. But full names (
ansible.builtin.copy) are unambiguous and don't clash with modules from collections you install later, and thefqcnrule in ansible-lint requires them anyway. So it's worth writing them in every new playbook.
- How do I run only part of a playbook?
Three tools, each for a different purpose. Tags (
--tags,--skip-tags) select groups of tasks. The--limitflag selects hosts. And--start-at-task "name"starts from a given task, which is useful for recovering after a failure. Before running for real, check the result with--list-tasksor--check --diff.
- Why does the command module always show "changed," and how do I fix it?
The module doesn't know whether the command changed the system's state, so it assumes it did. If the command only reads data, add
changed_when: false. If it should run only once, usecreatesorremoves. For trickier cases, define the condition yourself:changed_when: "'updated' in result.stdout". And if a dedicated module exists, replacecommandwith it.
- My playbook failed partway through. What do I do?
Read the
msgfield of the task that failed, rerun with-vor-vvvif needed, fix the cause, and simply run the playbook again: thanks to idempotence, the steps already completed won't cause harm. To avoid waiting, you can start from the right task with--start-at-task, or limit the run to the affected hosts with--limit. If the failure happened before a handler that was supposed to reload a service, remember--force-handlers.