How to have a nested loop with a fileglob pattern

ansible

I'm trying to create a set of authorized SSH keys for a set of users in Ansible. I have a users variable set up like so:

users:
  - { username: root, name: 'root' }
  - { username: user, name: 'User' }

In the same role, I also have a set of authorized key files in a files/public_keys directory, one file per authorized key:

roles/common/files/public_keys/home
roles/common/files/public_keys/work

I want to copy each public key to each user.

I have tried using the following task:

- name: copy authorized keys
  authorized_key: user={{ item.0.username }} key={{ item.1 }}
  with_nested:
    - users
    - lookup('fileglob', 'public_keys/*')

However, item.1 contains the literal string "lookup('fileglob', 'public_keys/*')", not each file path under files/public_keys.

Is there a way I can get a listing of the files/public_keys directory and copy each public key to each user?

Best Answer

The trick is to transform the fileglob return value into a list via the split function, so you can iterate over the values:

- name: copy authorized keys
  authorized_key: 
    user: "{{ item.0.username }}"
    key: "{{ lookup('file', item.1) }}"
  with_nested:
    - "{{ users }}"
    - "{{ lookup('fileglob', 'public_keys/*').split(',') }}"

Note that using bare variables, without {{ and }}, for with_items was deprecated in Ansible v2.