ansible- run first task on all servers and move to 2nd task

Viewed 83

how to do this logic.

run first task on all 4 servers in inventory and register in ls_file Then using 2nd task send a SINGLE mail to user with the contents of ls_file

   - name: check file
     shell: ls -l /var/abcd.txt
     register: ls_file




   - name: send mail to user
     mail:
       host: relay.server
       port: 25
       from: abcd@company.com
       to: manager <manager@company.com>
       subject: file availability
       

mail body should be as below.

       server1 - -rw-------. 1 root root 4405 Apr 20  2020 /var/abcd.txt
       server2 - -rw-------. 1 root root 4405 Apr 12  2020 /var/abcd.txt
       server3 - -rw-------. 1 root root 4405 Mar 15  2020 /var/abcd.txt
       server4 - -rw-------. 1 root root 4405 Apr 19  2020 /var/abcd.txt
1 Answers

In a nutshell:

  - name: send mail to user
    mail:
      host: relay.server
      port: 25
      from: abcd@company.com
      to: manager <manager@company.com>
      subject: file availability
      body: |-
        {% for servervars in hostvars | dict2items | map(attribute="value") | selectattr('ls_file', 'defined') %}
          {{ servervars.inventory_hostname }} - {{ servervars.ls_file.stdout }}
        {% endfor %}
    delegate_to: localhost
    run_once: true

This will create a line in your mail for any server where the variable ls_file exists.

Some refs worth to read:

Related