(solved) Ansible loop (subelements) in users>name, users>authorized_key_file and users>authorized_keyS

Viewed 15

i tried this test code :

- hosts: localhost
  gather_facts: no
  vars:
    users:
      - name: user1
        authorized_keys_file: authorized_keys_file_1.log
        authorized_keys:
          - key1
          - key2
      - name: user2
        authorized_keys_file: authorized_keys_file_2.log
        authorized_keys:
          - key1
  tasks:
    - name: List keys to add to authorized_key_file
      debug:
        msg: "User={{ item.0.name }} File={{ item.0.authorized_keys_file }} key={{ item.1 }}"
      loop:
        - "{{ users | subelements('authorized_keys') }}"

but i got the error :

The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'name'

expected result (to be used in ansible.posix.authorized_key) :

User=user1 File=authorized_keys_file_1 key=key1
User=user1 File=authorized_keys_file_1 key=key2
User=user2 File=authorized_keys_file_2 key=key1

Do you have an idea of what to do !?

Regards.

1 Answers

I found the solution ! "loop" must be on one line.

This is because i did a conversion from the old "with_subelements"

old version :

with_subelements:
  - "{{ users }}"
  - authorized_keys

New version (oneline...) :

loop: "{{ users | subelements('authorized_keys') }}"
Related