Using "when" in a template file

We have a playbook that will start the chronyd service periodically. If the service is down, it will be started. This causes the “changed” condition to be set to 1. This all works well. What I need to figure out is how can I use the “when: chrony.changed == 1” in our template file that we use to email our admins.

Currently, the template will send the service state for ALL hosts in the play. How can I only include those that were changed?

Service Check

Date generated: {{ ansible_date_time.month }}/{{ ansible_date_time.day }}/{{ ansible_date_time.year }} {{ ansible_date_time.time }}

{% if chrony is changed %}
{% for i in play_hosts | sort %}
Host: {{ i }}
      chronyd state: {{ hostvars[i]['chrony']['state'] }}
{% endfor %}
{% endif %}

Sorry, same issue. I have 2 hosts in my play. I stopped chronyd on the first host. The service was started on server 1 and didn’t need to be started on server 2. The email that came over has both hosts listed in it still.

[root@ansible ~]#ansible-playbook check_services.yml -K
BECOME password:

PLAY [services]***********************************************************************************************************************************************

TASK [setup] *************************************************************************************************************************************************
ok: [server1]
ok: [server2]

TASK [Start chronyd if not started] **************************************************************************************************************************
changed: [server1]
ok: [server2]

TASK [Prepare report] ****************************************************************************************************************************************
changed: [server1]

TASK [Send report to admins] *****************************************************************************************************************************
ok: [server1]

TASK [Delete local output file] ******************************************************************************************************************************
changed: [server1]

PLAY RECAP ***************************************************************************************************************************************************
server1 : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
server2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Email:

Service Check

Date generated: 03/01/2021 14:54:03

Ah, misinterpreted what you wanted, just put the if inside the for and
base it on the hostvar

{% for i in play_hosts | sort %}
{% if hostvars[i]['chrony'] is changed %}
Host: {{ i }}
chronyd state: {{ hostvars[i]['chrony']['state'] }}
{% endif %}
{% endfor %}

But you should really move to a 2nd play on hosts: localhost so you
wont send report X number of hosts that changed

That worked great! Thank you very much!

Harry