2.0 KiB
2.0 KiB
EX294 7.4: Error handling
Recover from a failure with block and rescue, decide what counts as a
failure, and stop a whole play when one host fails.
Before you start
This VM is the control node. The lab creates the user greg (password
Lab-Pass-1) and installs ansible-core. Work as greg, in
/home/greg/ansible: its ansible.cfg reads the inventory inventory,
logs in to the nodes as devops with greg's SSH key, and becomes root.
The managed nodes node1 (10.99.1.11) and node2 (10.99.1.12) are
AlmaLinux 10 containers, in the group nodes. For a root shell on a node,
sudo podman exec -it node1 bash.
Tasks
- Write
/home/greg/ansible/block.ymlfor all nodes: a block that tries to start a service that doesn't exist, arescuethat prints the failed task's name and message, and analwaysthat appends a line to/var/log/block.log. The recap showsrescued=1andfailed=0on every node, and the log file has the line. - Write
/home/greg/ansible/grep.yml, which runsgrepon the nodes for a pattern that isn't in the file, such aslab-pattern, in the file named by the variablegrep_file(by default/etc/hosts). Make the task fail only if the file is missing: the playbook passes as it is, and fails with-e grep_file=/etc/no-such-file. - Write
/home/greg/ansible/stop.yml: a play on all nodes with a task that fails on node1 only, then at least one more task. Make the play stop on every host as soon as node1 fails: the output showsNO MORE HOSTS LEFT, and the later tasks run on no host.
Hints
- In
rescue,ansible_failed_task.nameandansible_failed_result.msg. lineinfilewithcreate: truemakes the log file if it's missing.grepexits 0 on a match, 1 on none and 2 on an error such as a missing file; register the result and usefailed_whenon itsrc.ignore_errorsdoesn't change what a failure is./bin/falsewithwhen: inventory_hostname == 'node1', and a play keyword from the chapter's table.