5.1 Ansible Roles - Handlers and Blocks
We start to use handlers and blocks as well.
Task 1
- Create a playbook
myhandler.ymlwhich applies a rolehandlerroleonnode2. - The role
handlerroleshould do the following: - Create a directory
newdirin the folder/home/ansible. - If the folder didn’t exist before,
then do create a file
README.TXTin this folder containing the text “This folder was created at<timestamp>”. - The value of
<timestamp>should contain a quite accurate timestamp of whenansible-playbookwas run. - Run the playbook several times to see if it is really idempotent.
Hint
There is an ansible fact for when ansible was run.Solution Task 1
Below is a possible solution:
| |
Task 2
- Write a playbook
download.ymlwhich runs a roledownloaderonnode2. - The role
downloadershould try to download a file from a non-existing URL. - The role should be able to handle errors. Let it write the message “Download failed!” to standard output if the download task failed. The playbook must keep on running and shall not exit after this message.
- Regardless of download success, output a message at the end of the play informing that the download attempt has finished.
- Use a
block:to do these tasks. - Add another
ansible.builtin.debugtask after the block to confirm the run continues even after a download failed. - Run the playbook
download.yml.
Solution Task 2
| |
Note
Note the failed download task, but the playbook finished nonetheless.
All done?
Last modified December 3, 2025: Merge pull request #255 from puzzle/psc_corrections (139918b)