1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

We have older versions, Ansible 2.11.11 , Python 3.6
Actually this works, but not with set_fact like I tried first, but declared as variable, and I used instead "dict" some other name. Thanks
-1

your "dict" above is a list of dictionaries. you are trying to create a new list with just the names. Try

names_list: "{{ names_list | d([]) + [item.name] }}"
with_items: dict

2 Comments

I tried but getting Ansible undefined: ok: [localhost] => (item=dict) => { "ansible_facts": { "names_list": "[AnsibleUndefined]" }, "ansible_loop_var": "item", "changed": false, "item": "dict" }
@piercjs Undefined variables no clarity on what you are suggesting here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.