I’m trying to avoid having to put a key into every host_vars that uses a role that executes against multiple environments. Maybe I’m thinking about this wrong?
host_vars:
`
I’m trying to avoid having to put a key into every host_vars that uses a role that executes against multiple environments. Maybe I’m thinking about this wrong?
host_vars:
`
It seems that I can use selectattr to accomplish this.
Example:
@>>> from jinja2 import Template @>>> t = Template("{{ some_var|selectattr('allow', 'defined')|list }}") @>>> json = { @... "some_var": [ @... { @... "name": "one", @... "param": "foo", @... "allow": "True" @... }, @... { @... "name": "two", @... "param": "bar", @... } @... ] @... } @>>> t.render(json) u"[{'allow': 'True', 'name': 'one', 'param': 'foo'}]"
It would be nice if there was a way to assign the key with a default value. That way all the objects can be passed to with_items and skipped by when, which will show them in the log/output.
Hi,
You can always use " | default(‘value’) " filter if you’re not sure if a value is there. Value can be also a list or a dictionary.
Alternatively for ‘when’ you can test if the value is defined:
when: item.my_var is defined and my_var == …
kind regards
Pshem
Thanks, Pshem, using when/defineds/and get’s me exactly what I wanted.
I was using this initially and still getting a fatal error because when was trying to check an attribute that didn’t exist:
`
when:
It seems that syntax doesn’t short-circuit like you would expect and
to behave. You must use “when: item.my_var is defined and item.my_var.”
I also attempted to use the “|default(False)” approach, but I couldn’t figure out a way to apply the default value to only an attribute in a list of objects (“flag: False” in my example).
Thanks again for the help,