5.1 Ansible Roles - Handlers and Blocks

We start to use handlers and blocks as well.

Task 1

  • Create a playbook myhandler.yml which applies a role handlerrole on node2.
  • The role handlerrole should do the following:
  • Create a directory newdir in the folder /home/ansible.
  • If the folder didn’t exist before, then do create a file README.TXT in this folder containing the text “This folder was created at <timestamp>”.
  • The value of <timestamp> should contain a quite accurate timestamp of when ansible-playbook was run.
  • Run the playbook several times to see if it is really idempotent.
Solution Task 1

Below is a possible solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ cat myhandler.yml
---
- hosts: node2
  become: true
  roles:
    - handlerrole

$ ansible-galaxy init roles/handlerrole

$ cat roles/handlerrole/tasks/main.yml
---
- name: create directory
  file:
    path: /home/ansible/newdir
    state: directory
  notify: timestamp

$ cat roles/handlerrole/handlers/main.yml
---
- name: create readme with timestamp 
  copy:
    dest: /home/ansible/newdir/README.TXT
    content: "This folder was created at {{ ansible_date_time.iso8601 }}"    
  listen: timestamp

$ ansible-playbook myhandler.yml #<-- some changes when run the first time
$ ansible all -a "cat /home/ansible/newdir/README.TXT" #<-- show created files with it's content
$ ansible-playbook myhandler.yml #<-- no changes here, idempotent!

Task 2

  • Write a playbook download.yml which runs a role downloader on node2.
  • The role downloader should 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.
  • In all cases, output a message at the end of the play informing that the download attempt has finished.
  • Use a block: to do these tasks.
  • Run the playbook download.yml.
Solution Task 2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$ cat download.yml 
---
- hosts: node2
  become: true
  roles:
    - downloader

$ ansible-galaxy init roles/downloader

$ $ cat roles/downloader/tasks/main.yml 
---
# tasks file for roles/downloader
- block:
    - name: Download things from the internet
      get_url:
        url: http://www.not_existing_url.com/not_existing_file
        dest: /tmp/
  rescue:
    - debug:
        msg: "Download failed!"
  always:
    - debug:
        msg: "Download attempt finished."


$ ansible-playbook download.yml

All done?