Running task when difference filter is empty?

I have a playbook to update some servers. I want to send an email when a host fails to update. But I only want to send one email for all hosts that fail to update.

I figured out sending the email and getting the list of failed hosts but I’m having trouble with ONLY sending the email when a host fails. Currently the email sends every time I run a play.

tasks:
    - name: Update apt repo and cache
      ansible.builtin.apt:
        update_cache: yes
        force_apt_get: yes
        cache_valid_time: 3600

    - name: update apt list
      ansible.builtin.apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Upgrade packages
      ansible.builtin.apt:
        upgrade: dist
        force_apt_get: yes

    - name: check if reboot required
      register: reboot_required_file
      ansible.builtin.stat:
        path: /var/run/reboot-required
        get_checksum: false

    - name: Send email for failed updates
      # when:
      delegate_to: localhost
      run_once: true
      community.general.mail:
        body: |
          The below servers failed.
          {{ ansible_play_hosts_all|difference(ansible_play_hosts) }}
      ...

Is it possible to include a when: statement in the email task where it only sends an email if the result of {{ ansible_play_hosts_all|difference(ansible_play_hosts) }} is empty?

You want it the other way around, surely? Send an email when there’s a difference?

Either way, it’s possible.

# To alert when the difference is non-empty:
when: ansible_play_hosts_all | difference(ansible_play_hosts)
# Or, if you really only want alerts when there are no failures:
when: not ansible_play_hosts_all | difference(ansible_play_hosts)
3 Likes

Yes sorry. I had a brain error. I did want the email when there’s a difference.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.