Until now, whenever something failed in Aurora Store, Ansible always reacted the same way: it marked the host as failed, stopped running tasks on it and carried on with the others. That's good default behavior, but it isn't always what you need. Sometimes a "failure" isn't an error (a grep that finds nothing); sometimes an error on one server should stop the whole deployment; and, above all, sometimes you want to react to the failure: if the new version of the website doesn't work, go back to the previous one before a customer sees it. In this lesson you'll study what Ansible does when something fails, the difference between connection errors and task errors, how to decide for yourself what counts as a failure (failed_when) and what counts as a change (changed_when), when (and when not) to ignore errors, how to group tasks with block and handle failures with rescue and always, how to validate with assert and fail, and how to control the scope of a failure with any_errors_fatal, max_fail_percentage and meta. You'll apply all of this to Aurora with a home page deployment that rolls itself back if the check fails.
Contents
- What Ansible does when something fails
- Connection errors versus task errors
ignore_errors: carrying on despite the failureignore_unreachablefailed_when: deciding what a failure ischanged_when: deciding what a change isfailandassert: failing on purpose with clear messagesblock: grouping tasksrescueandalways: handling the failure- Practice: deploying the Aurora website with rollback
- The scope of a failure:
any_errors_fatalandmax_fail_percentage - Ending early:
meta: end_hostandmeta: end_play - Verifying and saving the work
- What Ansible does when something fails
The default behavior, which you've already seen many times:
flowchart TD
T[Task on web1, web2, db1] --> R{Result on each host}
R -- ok/changed --> C[The host moves on to the next task]
R -- failed --> F[The host is marked as failed<br/>and runs no more tasks in the playbook]
F --> H[Its pending handlers are discarded<br/>unless force_handlers]
C --> N{Any active hosts left in the play?}
N -- Yes --> S[Next task]
N -- No --> E[NO MORE HOSTS LEFT:<br/>the whole playbook stops]
The rules:
| Rule | Detail |
|---|---|
| Failure is per host | If a task fails on web1, web2 carries on normally |
| A failed host is left out | It runs no more tasks in that play or in the following plays of the same ansible-playbook run |
| If all the hosts in the play fail | NO MORE HOSTS LEFT is shown and the whole playbook stops: the following plays don't run |
| Handlers | The failed host's pending ones are discarded (unless force_handlers, which Aurora enabled in Lesson 5.1) |
| Exit code | 2 if some host failed, 4 if some host was unreachable (Lesson 3.1) |
The third rule has a direct consequence in site.yml: the database play has only one host, db1. If db1 fails, that play runs out of hosts and ansible-playbook stops before configuring the web servers. That's exactly what you want: there's no point deploying a website whose database has failed.
- Connection errors versus task errors
Ansible distinguishes two kinds of failure:
| Type | Status in the output | Typical cause | Counter in the PLAY RECAP |
|---|---|---|---|
| Connection | UNREACHABLE! |
The server is off, the network fails, SSH rejects the key, the host key changed | unreachable |
| Task | FAILED! |
The module returned an error: nonexistent package, a file that doesn't exist, a command with a nonzero exit code, a failed_when condition |
failed |
Remember it from Lesson 1.5, when you shut down web2:
fatal: [web2]: UNREACHABLE! => changed=false
msg: 'Failed to connect to the host via ssh: ssh: connect to host 192.168.56.12 port 22: No route to host'
unreachable: trueThe distinction matters because the tools in this lesson act on one type or the other:
ignore_errors,failed_when,rescueandmax_fail_percentagework with task errors (rescueandmax_fail_percentagealso take unreachable hosts into account).ignore_unreachableworks with connection errors.- None of them turns a syntax error or an undefined variable in the playbook itself into something valid: those errors mean the code is wrong, and they must be fixed.
For intermittent connection errors (an unstable network), the SSH connection plugin can retry: the retries option in the [ssh_connection] section of ansible.cfg. You don't need it in the lab.
ignore_errors: carrying on despite the failure
ignore_errors: carrying on despite the failureignore_errors: true means that, if the task fails, the host is not marked as failed:
- name: Check whether the old test website exists
ansible.builtin.command:
cmd: test -d /var/www/test
register: aurora_old_site
ignore_errors: true
changed_when: false
- name: Warn if the old test website is still there
ansible.builtin.debug:
msg: "/var/www/test still exists on {{ inventory_hostname }}"
when: aurora_old_site is succeededTASK [Check whether the old test website exists] *******************************
fatal: [web1]: FAILED! => changed=false
cmd: [test, -d, /var/www/test]
rc: 1
...
...ignoringThe output still shows the failure in red, followed by ...ignoring, and the PLAY RECAP counts it under ignored. The registered result keeps failed: true, so you can query it with is failed or is succeeded.
Use it very sparingly. Problems with ignore_errors:
- It hides real errors: the previous task also "fails" if
testdidn't exist or if there were no permissions, and you'd treat that the same as "the directory doesn't exist". - It's alarming in the output: a red
FAILED!on every run gets the team used to ignoring red. - It doesn't ignore everything: syntax errors, undefined variables or connection failures still stop the host.
There's almost always a better option: a module that doesn't fail (ansible.builtin.stat to find out whether a directory exists) or a failed_when that says exactly what a failure is (section 5). Keep ignore_errors for tasks whose failure really doesn't matter, such as an optional cleanup.
ignore_unreachable
ignore_unreachableignore_unreachable: true (on a task, a block or a play) means that an unreachable host is not dropped from the play: the task is marked as unreachable, but the host keeps trying the following ones.
- name: Take stock of the state of the Aurora servers
hosts: aurora
gather_facts: false
ignore_unreachable: true
tasks:
- name: Get the uptime
ansible.builtin.command:
cmd: uptime -p
register: aurora_uptime
changed_when: false
- name: Summarize the state
ansible.builtin.debug:
msg: "{{ inventory_hostname }}: {{ aurora_uptime.stdout | default('no connection') }}"With web2 shut down, the first task comes out UNREACHABLE for web2, but the second one runs for all of them and shows web2: no connection (the debug runs on the control node and doesn't need a connection). It's useful for reports and checks; don't use it in playbooks that change the configuration, because the following tasks would fail on the stopped host anyway.
failed_when: deciding what a failure is
failed_when: deciding what a failure isIn Lesson 3.7 you saw failed_when with getent and grep. Let's go deeper. failed_when replaces the module's failure criterion with a condition of your own, evaluated on the task's result (the one you'd capture with register):
- name: Count the active connections to the store database
ansible.builtin.command:
cmd: psql -tAc "SELECT count(*) FROM pg_stat_activity WHERE datname = 'aurora'"
become_user: postgres
register: aurora_db_connections
changed_when: false
failed_when: >-
aurora_db_connections.rc != 0 or
aurora_db_connections.stdout | int > (postgresql_max_connections | int * 0.9)- The task fails if
psqlfails or if more than 90% of the allowed connections are in use. In other words, it turns a query into a check. - You can refer to the result itself by its
registername insidefailed_when. - A list of conditions is combined with
and: it fails only if all of them are met.
This form (from Lesson 3.7) means "fail if rc isn't 0 and isn't 1", that is, only on real grep errors (code 2).
failed_when: falsemeans the task never fails. It's better thanignore_errorswhen you want the information without the redFAILED!, because it makes clear that it's intentional and doesn't clutter the output.
| I want… | Use |
|---|---|
| An "unusual" exit code not to count as a failure | failed_when: x.rc not in [0, 1] |
| A specific output to count as a failure | failed_when: "'ERROR' in x.stdout" |
| To query something without it ever failing | failed_when: false |
| To carry on even if it fails, knowing that it failed | ignore_errors: true (sparingly) |
changed_when: deciding what a change is
changed_when: deciding what a change ischanged_when is the companion of failed_when for the changed status. Since Lesson 3.7 you've mostly used it as changed_when: false on queries. Remember why it matters so much:
- A
commandorshellalways returnschangedunless you tell it otherwise. - A false
changednotifies handlers (Lesson 5.1): acommandthat notifiesReload nginxwould reload nginx on every run. - It breaks Aurora's golden rule: the second run must give
changed=0.
Beyond false, changed_when can express when a command has really changed something, based on its output:
- name: Create the pg_trgm extension in the store database
ansible.builtin.command:
cmd: psql -d aurora -c "CREATE EXTENSION IF NOT EXISTS pg_trgm"
become_user: postgres
register: aurora_ext
changed_when: "'already exists' not in aurora_ext.stderr"CREATE EXTENSION IF NOT EXISTS writes a notice extension "pg_trgm" already exists, skipping to standard error when it does nothing. The task reports a change only when the extension has been created. (It's an example: for extensions there's the community.postgresql.postgresql_ext module, which is idempotent by itself and is always preferable to a command.)
changed_when and failed_when can be combined in the same task. Ansible evaluates changed_when first and then failed_when.
fail and assert: failing on purpose with clear messages
fail and assert: failing on purpose with clear messagesSometimes the failure doesn't come from a module, but from a situation you detect: a parameter out of range, an unsupported system, an unexpected state. There are two modules for that:
| Module | When | Example |
|---|---|---|
ansible.builtin.fail |
Fail if a condition is met (with when) |
fail: msg: "..." + when: ... |
ansible.builtin.assert |
Check one or more conditions that must hold | that: [...], fail_msg, success_msg |
- name: Reject unsupported systems
ansible.builtin.fail:
msg: >-
Aurora Store has only been tested on Ubuntu 24.04;
{{ inventory_hostname }} has {{ ansible_facts['distribution'] }}
{{ ansible_facts['distribution_version'] }}.
when: ansible_facts['distribution_version'] is version('24.04', '<')- name: Check the free space on the root filesystem
ansible.builtin.assert:
that:
- (ansible_facts['mounts'] | selectattr('mount', 'equalto', '/') | first)['size_available'] > 2 * 1024 * 1024 * 1024
fail_msg: "{{ inventory_hostname }} has less than 2 GB free on /"
quiet: trueassert is more expressive when there are several conditions, and its that list reads like a specification. quiet: true avoids the detailed output when everything is fine.
A good error message says what fails, where and, if possible, what value it had. "Configuration error" forces you to investigate; "nginx_port must be between 1 and 65535 (current value: 80800)" gets fixed in seconds.
Practice: checking the ranges of the nginx role
In Lesson 4.6 you saw that argument_specs checks types, but not ranges ("for that, assert"). Add the check at the beginning of roles/nginx/tasks/main.yml, before the imports:
---
- name: Check the role parameters
ansible.builtin.assert:
that:
- nginx_port | int >= 1 and nginx_port | int <= 65535
- nginx_upstream_port | int >= 1 and nginx_upstream_port | int <= 65535
- nginx_worker_connections | int >= 1
fail_msg: >-
nginx parameters out of range on {{ inventory_hostname }}:
nginx_port={{ nginx_port }}, nginx_upstream_port={{ nginx_upstream_port }},
nginx_worker_connections={{ nginx_worker_connections }}.
Ports must be between 1 and 65535 and worker_connections must be greater than 0.
quiet: true
- name: Install nginx
ansible.builtin.import_tasks: install.yml
# ... (the rest of the imports don't change)Each condition converts the value with int before comparing it: that way it works the same if the value arrives as text (for example, from -e).
Try it in check mode:
TASK [nginx : Check the role parameters] ***************************************
fatal: [web1]: FAILED! => changed=false
assertion: nginx_port | int >= 1 and nginx_port | int <= 65535
evaluated_to: false
msg: 'nginx parameters out of range on web1: nginx_port=80800, nginx_upstream_port=80, nginx_worker_connections=1024. Ports must be between 1 and 65535 and worker_connections must be greater than 0.'The value passes the argument_specs validation (it's an integer), and it's the assert that stops it, before anything is touched.
block: grouping tasks
block: grouping tasksA block groups several tasks so they can be treated as a unit:
- name: Configure access for the reporting servers
when: aurora_reporting_enabled | default(false) | bool
become_user: postgres
block:
- name: Create the reports schema
community.postgresql.postgresql_schema:
name: reports
database: aurora_analytics
- name: Grant read permissions to the reporting user
community.postgresql.postgresql_privs:
database: aurora_analytics
roles: aurora_reporting
type: schema
objs: reports
privs: USAGE- The block's keywords (
when,become,become_user,tags,no_log,ignore_errors…) apply to each task in the block, as withimport_tasks. In particular,whenis evaluated on each task, not just once. - The block can have a
name(recommended: it shows up in the code's documentation, though not in the output). - By convention, Aurora writes the block's keywords before
block:, so that they can be seen at a glance without scrolling down to the end of the task list.
The example is illustrative (Aurora doesn't have reporting servers yet). The most important use of block is the one in the next section.
rescue and always: handling the failure
rescue and always: handling the failureblock accepts two additional sections, like a try/catch/finally in programming languages:
- name: Example structure
block:
- name: Task that may fail
ansible.builtin.command:
cmd: /bin/false
rescue:
- name: Runs only if something in the block fails
ansible.builtin.debug:
msg: "{{ ansible_failed_task.name }} has failed"
always:
- name: Always runs, whether or not anything failed
ansible.builtin.debug:
msg: Cleanupflowchart TD
B[block] -->|all ok| A[always]
B -->|one fails| R[rescue]
R -->|rescue finishes fine| A2[always<br/>the host is NOT left failed]
R -->|rescue fails| A3[always<br/>the host is left failed]
A --> S[Next task]
A2 --> S
A3 --> X[Host out of the play]
The rules:
| Section | When it runs | Effect on the host |
|---|---|---|
block |
Always (unless there's a condition) | If a task fails, the remaining ones in the block are skipped |
rescue |
Only if some task in the block failed |
If it finishes without errors, the failure is considered rescued: the host stays active |
always |
Always, after block (and after rescue if it ran) |
It doesn't change the host's state |
Inside rescue you have two special variables:
ansible_failed_task: the task that failed (for example,ansible_failed_task.name).ansible_failed_result: its result (for example,ansible_failed_result.msg).
A detail that's often overlooked: if rescue finishes fine, the error disappears. The PLAY RECAP counts it under rescued, but failed stays at 0 and the exit code is 0. If the failure should still be a failure after you've "fixed" what you can (for example, going back to the previous version), end the rescue with a fail task.
- Practice: deploying the Aurora website with rollback
Until now, the home page is published and then, in the post_tasks of webservers.yml, the website is checked. If the check fails, the server is already serving the new, broken page. You're going to make the aurora_app role deploy the page, check it on the same server and, if it doesn't work, restore the previous one.
10.1. A version for the website
So you know which version each server is serving, the website will show a version number. Add two parameters to roles/aurora_app/defaults/main.yml:
# Version of the website being deployed (shown on the home page).
aurora_app_version: "1.0.0"
# URL the server itself uses to check the website after deploying it.
aurora_app_check_url: http://localhost/The version goes in quotes: YAML would already treat 1.0.0 as text, but it would turn 1.10 into the number 1.1 (Lesson 3.2). Always write it as text.
Add them to roles/aurora_app/meta/argument_specs.yml too:
aurora_app_version:
type: str
default: "1.0.0"
description: Version of the website being deployed. It's shown on the home page.
aurora_app_check_url:
type: str
default: http://localhost/
description: URL the server uses to check the website after deploying it.In inventory/group_vars/webservers.yml, next to the aurora_app parameters (the role doesn't read nginx_port, so the inventory does the wiring):
And in roles/aurora_app/templates/index.html.j2, change the last line of the body:
<p><small>Version {{ aurora_app_version }} - Served by {{ inventory_hostname }} - {{ aurora_app_domain }}</small></p>10.2. The deployment with block, rescue and always
In roles/aurora_app/tasks/main.yml, replace the "Publish the store home page" task with this block, preceded by a flush_handlers:
- name: Apply the web server's pending changes
ansible.builtin.meta: flush_handlers
- name: Deploy the store home page
block:
- name: Publish the store home page
ansible.builtin.template:
src: index.html.j2
dest: "{{ aurora_app_web_root }}/index.html"
owner: root
group: root
mode: "0644"
backup: true
register: aurora_app_index
- name: Check that the store serves the deployed version
ansible.builtin.uri:
url: "{{ aurora_app_check_url }}"
return_content: true
register: aurora_app_check
failed_when: >-
aurora_app_check.status != 200 or
('Version ' ~ aurora_app_version) not in (aurora_app_check.content | default(''))
when:
- aurora_app_index is changed
- not ansible_check_mode
rescue:
- name: Restore the previous version of the home page
ansible.builtin.copy:
src: "{{ aurora_app_index.backup_file }}"
dest: "{{ aurora_app_web_root }}/index.html"
remote_src: true
owner: root
group: root
mode: "0644"
when: aurora_app_index.backup_file is defined
- name: Stop the deployment on this server
ansible.builtin.fail:
msg: >-
Version {{ aurora_app_version }} has not passed the check on
{{ inventory_hostname }} ({{ ansible_failed_task.name }}: {{ ansible_failed_result.msg | default('no details') }}).
{{ 'The previous version has been restored.' if aurora_app_index.backup_file is defined else 'There was no previous version to restore.' }}
always:
- name: Delete the home page backup
ansible.builtin.file:
path: "{{ aurora_app_index.backup_file }}"
state: absent
when: aurora_app_index.backup_file is definedAnalyze it piece by piece:
meta: flush_handlersbefore the block: the check needs nginx to be serving with its final configuration already. On a freshly created server, the site configuration has been written in thenginxrole, but the reload (a handler) would happen at the end of the play; without theflush, the check would fail on the first deployment. This is the use offlush_handlersyou saw in Lesson 5.1: a later task needs the change already applied.backup: true: if the page changes, Ansible keeps the previous one and returns its path inaurora_app_index.backup_file. That's the "previous version" to go back to.- The check only happens if the page has changed (if there's no deployment, there's nothing to check) and not in
--checkmode. In a simulation the page isn't really written, so the server would keep showing the old version and the check would always fail. It's true thaturidoesn't support check mode and would be skipped on its own, but the condition puts the intention in writing and protects the block if one day someone addscheck_mode: falseto the task (as you did in thepost_tasksofwebservers.ymlin Lesson 3.7). It fails if the response isn't 200 or doesn't containVersion 1.0.0(or whichever applies): that way it detects both a website that's down and an old or wrong page. Thedefault('')covers the case where there's no content (for example, if it couldn't connect). rescuerestores the copy (if there is one; on a server's first deployment there's no previous version) and ends withfail: the server is left with the good version, but the deployment is reported as failed, with a message saying which task failed and why. Without thatfail, thePLAY RECAPwould sayfailed=0and nobody would find out.alwaysdeletes the backup in every case. Here it's essential: the directory is the web root, and nginx would serve theindex.html.*~files to anyone (the warning aboutbackupin Lesson 5.2).
10.3. First deployment: version 1.0.0
TASK [aurora_app : Apply the web server's pending changes] *********************
TASK [aurora_app : Publish the store home page] ********************************
changed: [web1]
changed: [web2]
TASK [aurora_app : Check that the store serves the deployed version] ***********
ok: [web1]
ok: [web2]
TASK [aurora_app : Delete the home page backup] ********************************
changed: [web1]
changed: [web2]The page changes (the version line is added), the check passes and the copy is deleted. Run it again: the page doesn't change, the check and the cleanup are skipped (skipping) and the result is changed=0.
10.4. A deployment that fails
Simulate a new version with a problem. The simplest way to make the check fail without breaking anything is to have it check a URL that doesn't exist:
ansible-playbook webservers.yml --limit web1 \
-e aurora_app_version=1.1.0 -e aurora_app_check_url=http://localhost/does-not-existTASK [aurora_app : Publish the store home page] ********************************
changed: [web1]
TASK [aurora_app : Check that the store serves the deployed version] ***********
fatal: [web1]: FAILED! => changed=false
...
status: 404
url: http://localhost/does-not-exist
TASK [aurora_app : Restore the previous version of the home page] **************
changed: [web1]
TASK [aurora_app : Stop the deployment on this server] *************************
fatal: [web1]: FAILED! => changed=false
msg: 'Version 1.1.0 has not passed the check on web1 (Check that the store serves the deployed version: Status code was 404 and not [200]: HTTP Error 404: Not Found). The previous version has been restored.'
TASK [aurora_app : Delete the home page backup] ********************************
changed: [web1]
PLAY RECAP *********************************************************************
web1 : ok=... changed=3 unreachable=0 failed=1 skipped=... rescued=1 ignored=0rescued=1: therescueran.failed=1: the finalfailkeeps the deployment as failed, and the following tasks in the play (static pages,post_tasks) don't run onweb1.alwaysran anyway, despite the failure inrescue.
Check that web1 is still serving the good version and that no copies are left in the web root:
curl -s http://192.168.56.11/ | grep Version
ansible web1 -m ansible.builtin.find -a "paths=/var/www/aurora patterns='*~'"The find returns matched: 0. The store has never stopped working: for a few moments web1 served the 1.1.0 page (which in this case was fine; what failed was the check), and it was restored as soon as the check failed. In Lesson 5.7 you'll see how to take the server out of the load balancer before deploying, so that not even those moments are visible.
A word of caution about scope: this rollback protects the home page, which is what the role deploys today. When Aurora has a real application, the technique will be the same, but the unit that gets deployed and restored will be the directory of the whole version (a common pattern is to have each version in its own directory and a current symbolic link that is switched atomically).
- The scope of a failure:
any_errors_fatal and max_fail_percentage
any_errors_fatal and max_fail_percentageBy default, a failure only affects the host on which it occurs. In some playbooks you want the opposite:
| Keyword (play or block) | Effect | When |
|---|---|---|
any_errors_fatal: true |
If one host fails, the play stops on all of them (they finish the current task and do nothing more), and the playbook doesn't continue | Changes that must be applied everywhere or nowhere: schema migrations, cluster changes |
max_fail_percentage: N |
If more than N% of the hosts fail, the play stops on all of them | Deployments on large fleets: tolerate an isolated failure, but not a general outage |
- name: Migrate the store database schema
hosts: dbservers
become: true
any_errors_fatal: true
tasks:
- name: ...Details:
max_fail_percentagecounts failed and unreachable hosts, and the condition is "more than": with25and 4 hosts, 1 failure (25%) is tolerated, 2 (50%) stop the play.max_fail_percentage: 0is, in practice, equivalent to "no failures".- Both options shine when the play runs in batches with
serial: a failure in the first batch prevents the second one from being touched. That's what you'll do in Lesson 5.7 with the Aurora web servers, wheremax_fail_percentageis calculated per batch. any_errors_fatalcan also be set on a block, so that only a critical section has that behavior.
Aurora doesn't adopt either of them in this lesson: the dbservers play has a single host (if it fails, the playbook already stops, section 1), and the web servers will get their policy in Lesson 5.7.
- Ending early:
meta: end_host and meta: end_play
meta: end_host and meta: end_playSometimes there isn't an error, but a reason not to continue. meta tasks allow this without marking failures:
meta |
Effect |
|---|---|
end_host |
Ends the play for this host, without an error. The others carry on |
end_play |
Ends the play for all hosts, without an error |
end_batch |
With serial, ends the current batch (Lesson 5.7) |
clear_host_errors |
Brings back into the play the hosts that had failed (very exceptional use) |
A useful example: excluding from a run the servers that are under maintenance, marked with a variable in host_vars:
pre_tasks:
- name: Skip the servers under maintenance
ansible.builtin.meta: end_host
when: aurora_maintenance | default(false) | boolIf inventory/host_vars/web2.yml had aurora_maintenance: true, the play would end for web2 at the start, without failures, and web1 would carry on normally. It's more explicit than remembering to use --limit '!web2'.
And end_play, for example, to do nothing outside a maintenance window:
- name: Don't deploy outside the maintenance window
ansible.builtin.meta: end_play
when: not (aurora_force_deploy | default(false) | bool) and now().hour not in range(6, 9)(now() is an Ansible function that returns the date and time of the control node.) These two examples aren't incorporated into Aurora; keep them in mind for when you need them.
- Verifying and saving the work
The first run may show changes if you didn't do section 10.3; the second must finish with changed=0, failed=0 and rescued=0 on all hosts. Check the version served on both websites:
for ip in 192.168.56.11 192.168.56.12; do curl -s http://$ip/ | grep -o 'Version [0-9.]* - Served by web[0-9]'; doneSave the work:
git add inventory/ roles/
git commit -m "Home page deployment with check and rollback; nginx ranges with assert"Common Mistakes and Tips
- A
rescuethat "swallows" the error: ifrescuefinishes fine, thePLAY RECAPsaysfailed=0. End it withfailwhen the failure should remain a failure. ignore_errorsas a universal solution: it hides real problems. Prefer a module that doesn't fail,failed_whenwith the exact criterion, orfailed_when: falsefor queries.- A
failed_whenthat gives an undefined variable error: the condition uses a field that doesn't exist in every case (for example,contentwhen there was no connection). Usedefault. - Checks that fail in
--check: in a simulation, changes aren't really applied. Make the checks conditional onnot ansible_check_mode. - Forgotten backups:
backup: trueleaves files that pile up, and in a web root they get published. Delete them inalwaysor don't usebackupin those directories. - Expecting
ignore_errorsto ignore an undefined variable: it doesn't. Code errors get fixed, not ignored. - Tip: when you write an
assertor afail, think about whoever will read it at three in the morning. Include the host, the variable and its value.
Exercises
Exercise 1: Choosing the tool
For each case, choose between failed_when, changed_when, ignore_errors, ignore_unreachable, assert, block/rescue or any_errors_fatal, and justify your choice:
grep -c aurora /etc/hostsreturns 1 when it finds nothing.- A report that must list the state of all the servers even if one of them is off.
- A change on the three nodes of a cluster that can't be left applied on only some of them.
- Checking that
aurora_app_db_portis different from 0 before writingdb.conf. - If downloading a package from an internal repository fails, trying to download it from an alternative repository.
Exercise 2: Rescuing without hiding
Write a block that tries to install the aurora-monitor package (which doesn't exist) on web1 and, if it fails, shows a warning with the name of the failed task and its message, without the host being left failed. Which PLAY RECAP counters reflect what happened?
Exercise 3: Reviewing the deployment
In section 10, what would happen if you removed the not ansible_check_mode condition from the check and ran ansible-playbook webservers.yml --check -e aurora_app_version=1.2.0? And if you removed the always section?
Solutions
Exercise 1.
failed_when: x.rc not in [0, 1](andchanged_when: false): code 1 is a valid result ("zero matches"), not an error.ignore_unreachable: trueon the play: hosts that are off aren't dropped from the play and the summary can show them as "no connection".any_errors_fatal: true: a failure on any node stops the change on all of them.assertwiththat: aurora_app_db_port | int > 0and a clearfail_msg, or better still inargument_specsif it were an expressible range (it isn't:assert).block(download from the internal repository) +rescue(download from the alternative one). If therescueworks, the host carries on without errors.
Exercise 2.
- name: Try out a rescue
hosts: web1
become: true
gather_facts: false
tasks:
- name: Install the store monitor if it's available
block:
- name: Install aurora-monitor
ansible.builtin.apt:
name: aurora-monitor
state: present
rescue:
- name: Warn that the monitor isn't available
ansible.builtin.debug:
msg: "Warning: '{{ ansible_failed_task.name }}' failed: {{ ansible_failed_result.msg }}"The PLAY RECAP shows failed=0 and rescued=1. The failed task appears in red in the output, but the host stays active and the exit code is 0. That's the right behavior for something optional; for something essential, the rescue should end with fail.
Exercise 3. Without not ansible_check_mode, as the task stands, nothing visible would happen: uri doesn't support check mode and would be skipped. But all it would take is for someone to add check_mode: false to it (so that the check "also works in simulation") for the following to happen: template reports changed but doesn't write the page; the check, actually executed, would receive the old page, without Version 1.2.0, and would fail. It would go into rescue, whose copy and fail would be simulated, and the --check would finish with failed=1 even though the real deployment would work: a false positive that would make the simulation useless. Without always: after every deployment with changes, an index.html.<pid>.<date>~ copy would be left in /var/www/aurora, accessible from the browser, and they would pile up over time.
Conclusion
You now control what Ansible does when something fails. You know that a failure affects the host on which it occurs, that a play with no active hosts stops the playbook, and that connection errors (UNREACHABLE) and task errors (FAILED) are handled with different tools: ignore_unreachable for the former; failed_when, ignore_errors (sparingly), block/rescue/always, any_errors_fatal and max_fail_percentage for the latter. You've gone deeper into changed_when and failed_when, you've used assert to check the ranges of the nginx role and fail with messages that explain what happened, and you know meta: end_host and meta: end_play for ending without errors. In Aurora, the aurora_app role deploys the home page with its version (aurora_app_version), checks it on the server itself and, if it fails, restores the previous one, reports the failure and cleans up the backup. The Aurora playbooks now have a lot of tasks, and you don't always want to run all of them: sometimes you just need to deploy a new version of the website, or review the users, without waiting for packages and firewalls to be checked. In the next lesson, Tags and Selective Execution, you'll learn to tag tasks, blocks and roles so you can run only the part you need.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
