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?