I have a list of dictionaries like so:
myvar:
- host: host1
version: 2
- host: host2
version: 5
- host: host3
version: 4
I’m trying to write an assert task that fails when any of the hosts have a version > 3 and I also want the failure message to include all such hosts. E.g.:
The following hosts have a version greater than 3: host2, host3
The last part is key. I want to display all the hosts that failed the check, not just the first one. Thanks.
It would be easier to define an intermediate variable like hosts_with_version_above_threshold
because it will be reused for both the validation and the error message. To filter out the hosts with a version above the threshold we can use the selectattr
Jinja2 filter, and to show only the hosts in the message - map
(see Loops and list comprehensions for details):
---
- name: Validate the version numbers
hosts: localhost
connection: local
gather_facts: false
vars:
myvar:
- host: host1
version: 2
- host: host2
version: 5
- host: host3
version: 4
threshold: 3
hosts_with_version_above_threshold: "{{ myvar | selectattr('version', 'gt', threshold) }}"
message: "The following hosts have a version greater than {{ threshold }}:"
tasks:
- name: Assert the version numbers
assert:
that: hosts_with_version_above_threshold is not defined or not hosts_with_version_above_threshold
fail_msg: "{{ message }} {{ hosts_with_version_above_threshold | map(attribute='host') | join(', ') }}"