The real goal here is to perform an action only when at least one of inventory_hostname groups from group_names matches one group from another list of groups (in this example: git|local|ntopng
) .
This is defined within a role, so I cannot use the list - hosts:
.
For instance, to print all hostname variables only when inventory_hostname belong to at least one of git,local or ntopng groups,I tried this:
`
- name: Print all variables for “{{ inventory_hostname }}” system device (except any role parameters)
debug:
var: hostvars[inventory_hostname]
when: group_names | map(‘regex_search’, “^(git|local|ntopng)$”) | list | length > 0
`
It does not work as expected, because the length always returns the number of groups within group_names. It seems that length considers a null element as defined and counts it.
“is defined” does not work either for the same reason.
I cannot find a way to test if at least one element of the search is not null.
Any suggestion?
The real goal here is to perform an action only when at least one of inventory_hostname groups from group_names matches one group from another list of groups (in this example: git|local|ntopng
) .
This is defined within a role, so I cannot use the list - hosts:
.
For instance, to print all hostname variables only when inventory_hostname belong to at least one of git,local or ntopng groups,I tried this:
`
- name: Print all variables for “{{ inventory_hostname }}” system device (except any role parameters)
debug:
var: hostvars[inventory_hostname]
when: group_names | map(‘regex_search’, “^(git|local|ntopng)$”) | list | length > 0
`
That’s overly complicated, unless you’ve misstated your requirements.
when: group_names | intersect(['git', 'local', 'ntopng'])
It does not work as expected, because the length always returns the number of groups within group_names. It seems that length considers a null element as defined and counts it.
“is defined” does not work either for the same reason.
I cannot find a way to test if at least one element of the search is not null.
While you shouldn’t be using regex or complex filtering at all for this particular thing, you might find this information useful in the future.
A null element is still an element. You can filter out elements you don’t want.
`
when: group_names | map(‘regex_search’, “^(git|local|ntopng)$”) | select | list
`
Though it’s simpler to do that in the first place instead of map.
when: group_names | select('match', '^(git|local|ntopng)$') | list