I have the following dictionary:
"dict": [ { "name": "a", "surname": "b" }, { "name": "c", "surname": "d" }, { "name": "e", "surname": "f" } ]
I am trying to extract just "name" values into one list like this one:
names_list: ["a","c","e"]
It should be very simple but I'm not getting the result. This is what I tried:
- set_fact:
names_list: "{{ dict | json_query('[*].name') }}"
and also:
- set_fact:
names_list: "{{ dict | map(attribute='name') | list }}"
but I'm getting either "none" or "ansible undefined".
What I'm missing here?
Thanks.
Short answer: Rename the variable dict.
Details: In Ansible 2.14.3, Python 3.9.16, jinja version = 3.1.2 both options work as expected
- set_fact:
names_list1: "{{ dict|map(attribute='name')|list }}"
names_list2: "{{ dict|json_query('[*].name') }}"
give
names_list1: [a, c, e]
names_list2: [a, c, e]
But, I got the warning:
[WARNING]: Found variable using reserved name: dict
Example of a complete playbook for testing
- hosts: localhost
vars:
dict:
- {name: a, surname: b}
- {name: c, surname: d}
- {name: e, surname: f}
# names_list1: "{{ dict|map(attribute='name')|list }}"
# names_list2: "{{ dict|json_query('[*].name') }}"
tasks:
- set_fact:
names_list1: "{{ dict|map(attribute='name')|list }}"
names_list2: "{{ dict|json_query('[*].name') }}"
- debug:
var: names_list1|to_yaml
- debug:
var: names_list2|to_yaml