Search code examples
arraysansibleldap

How can I build list from the values of a dictionary?


I have a list of AD users and trying to create a distinguishedName-list

vars:
  admin_users: "user1;user2"
  tasks:
  - set_fact:
    admin: "{{ admin_users.split(';') }}"

  - name: Search account
    community.general.ldap_search:
    <...>
    loop: "{{ admin }}"
    register: ldap_result

  - name: Build DN-array
    set_fact:
      group: "{{ group | default([]) }} +  {{ item.value | json_query(query) }}"
    with_dict: "{{ ldap_result.results }}"
    when: item.key == 'results'
    vars:
      query: "[*].distinguishedName"

  - debug:
    var: "{{ group }}"

And get

"<class 'list'>": "VARIABLE IS NOT DEFINED!"

Also tried

group: "{{ group | default([]) }} + [ {{ item.value | json_query(query) }} ]"
group: "{{ group | default([]) }} + {{ [ item.value | json_query(query) ] }}"

get same message

"<class 'list'>": "VARIABLE IS NOT DEFINED!"

and

group: "{{ group | default([]) }} + [ '{{ item.value | json_query(query) }}' ]"

Then I get the error

FAILED! => {"msg": "template error while templating string: expected
token ',', got 'CN'. String: {{[] + [ '['CN=***']' ] + [ '['CN=***']' ]}}"}

Any tips?


Solution

  • Ok, that's right, I just needed to use a construction like this

        <...>
        group: "{{ group | default([]) }} + [ {{ item.value | json_query(query) }} ]"
        <...>
        - debug: msg="{{ group }}"
    

    not this

    - debug:
        var: "{{ group_list_two }}"
    

    correct output

    ok: [localhost] => {
        "msg": [
            [
                "CN=***"
            ],
            [
                "CN=***"
            ]
        ]
    }