A list of list_obj
objects has been created:
[
{"obj" : "host-01", "join" : "false"},
{"obj" : "host-02", "join" : "false"}
]
In the task, I select the required object from the list using the selectattr
method in the when
condition on the object attribute:
- name: Select connection flag
debug:
msg: {{ ??? }}
when: "{{ list_obj | selectattr('obj', 'eq', host_name) }}"
I can't figure out how to output the value of the join
attribute of the selected object in msg
.
A list of list_obj
objects has been created:
[
{"obj" : "host-01", "join" : "false"},
{"obj" : "host-02", "join" : "false"}
]
In the task, I select the required object from the list using the selectattr
method in the when
condition on the object attribute:
- name: Select connection flag
debug:
msg: {{ ??? }}
when: "{{ list_obj | selectattr('obj', 'eq', host_name) }}"
I can't figure out how to output the value of the join
attribute of the selected object in msg
.
2 Answers
Reset to default 2selectattr
is simply a way of filtering a list, it cannot assess if your result is supposed to be a single element of the initial list or not, so, you will still get a list back (or rather an iterator):
jinja-filters.selectattr(value: 't.Iterable[V]', *args: Any, **kwargs: Any) → 't.Iterator[V]'
As pointed by the filter signature displayed in Jinja's documentation
So, you will need to select the first element of your list, either via .0
or [0]
, or via the first
filter.
Then you can select the join
attribute.
So,
# Either
msg: "{{ (list_obj | selectattr('obj', 'eq', host_name)).0.join }}"
# Or
msg: "{{ (list_obj | selectattr('obj', 'eq', host_name))[0].join }}"
# Or
msg: "{{ (list_obj | selectattr('obj', 'eq', host_name) | first).join }}"
Given the list for testing
list_obj:
- {obj: host_01, join: false}
- {obj: host_02, join: false}
- {obj: host_03, join: true}
Convert the list to a dictionary
dict_obj: "{{ list_obj | items2dict(key_name='obj', value_name='join') }}"
gives
dict_obj:
host_01: false
host_02: false
host_03: true
Then, the selection is trivial. For example,
- debug:
var: dict_obj[inventory_hostname]
Example of a complete playbook for testing
- hosts: all
vars:
list_obj:
- {obj: host_01, join: false}
- {obj: host_02, join: false}
- {obj: host_03, join: true}
tasks:
- name: Create dictionary dict_obj
run_once: true
block:
- set_fact:
dict_obj: "{{ list_obj | items2dict(key_name='obj', value_name='join') }}"
- debug:
var: dict_obj
- debug:
var: dict_obj[inventory_hostname]