Reputation: 367
I'm writing an Ansible Template in Jinja, which has the following pattern:
# Inventory
[Group1]
vm1 cluster=clusterName
[Group2]
vm2
Notice that the second group does not have the property cluster
defined.
# Task Definition
vars:
potential_seeds: "{{groups.all | map('extract', hostvars) | groupby('cluster') | list}}"
This, of course, results in an obvious error:
"the field 'vars' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'cluster'
I'm in need of filtering the list in a way that it only groups the dictionaries that have cluster
defined.
Upvotes: 3
Views: 3833
Reputation: 68239
You can use selectattr
prior to groupby
:
groups.all |
map('extract', hostvars) |
selectattr('cluster','defined') |
groupby('cluster') |
list
This will select only elements with cluster
property defined before grouping.
Upvotes: 9