1

What am I doing wrong?

admins:
  - name: "{{ vault_admin_user1_name }}"
    sshkey:
      - "{{ vault_admin_user1_pubkeyA }}"
      - "{{ vault_admin_user1_pubkeyC }}"

- name: Set up multiple authorized keys for users
  ansible.posix.authorized_key:
    user: '{{ item.name }}'
    state: present
    key: '{{ item.sshkey }}'
  loop: "{{ admins|subelements('sshkey.item') }}"

When I try to iterate over admin's properties I got:

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ admins|subelements('sshkey.item') }}): the key item should point to a dictionary, got '[1st key,2nd key...]}

hc_dev
  • 8,389
  • 1
  • 26
  • 38
mkozub
  • 23
  • 2
  • Your question is unclear. What should the final `loop` look like? What is inside your `admins` dictionary or list? – hc_dev Jun 05 '22 at 17:55
  • @hc_dev - I'm trying to loop both over users in admins list and for each user i want to add multiple ssh keys – mkozub Jun 05 '22 at 17:57

1 Answers1

1

If you want to:

loop over users [name] in admins list

and for each user add multiple ssh keys [sshkey]

(I added property names in brackets)

You could use 3 ways:

Use with_subelements

- ansible.posix.authorized_key:
    user: '{{ item.0.name }}'
    state: present
    key: '{{ item.1 }}'
  with_subelements:
    - "{{admins}}"
    - sshkey

where {{admins}} is your outer-loop, becomes item.0 (outer element) and sshkey is your inner-loop, becomes item.1 (inner element).

See the example in Ansible with_subelements and compare the Ansible docs with_subelements.

Use loop with subelements

- ansible.posix.authorized_key:
    user: "{{ item.0.name }}"
    state: "{{ item.0.state | default('present') }}"
    key: "{{ item.1 }}"
  loop: "{{ admins | subelements('sshkey', 'skip_missing=True') }}"

Now the admins before pipe-symbol (filter) is the outer-element, whereas sshkey is the inner-element .

See the article explaining it well for a similar case:

Jinja for-loop

Alternatively you could use Jinja2's loops like explained in Iterating through Python dictionary with Jinja2.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
hc_dev
  • 8,389
  • 1
  • 26
  • 38