16

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?

mipadi
  • 315
  • 2
  • 3
  • 11

3 Answers3

12

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.

conorsch
  • 349
  • 3
  • 10
0

for me this was working only in this form

    - name: Set up authorized keys for root
      authorized_key:
        user: root
        state: present
        key: "{{ lookup('file', item) }}"
      with_fileglob: 'public_keys/*.pub'
mati kepa
  • 179
  • 1
  • 4
0

You might have to significantly rewrite your command, but there's provision for looping over fileglobs

from the example:

- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
  with_fileglob:
    - /playbooks/files/fooapp/*

Other promising options are Looping over Subelements which is actually illustrated by SSH keys

Tom O'Connor
  • 27,480
  • 10
  • 73
  • 148
  • 3
    I know you can loop over file globs using `with_fileglob`; I'm just not sure how to use that in conjunction with a nested loop. Looping over subelements _could_ work, but I'm hoping I don't have to manually specify the entire list of keys I want to copy, since I _should_ just be able to get that as a list (using `with_fileglob`). – mipadi Dec 07 '14 at 20:45
  • I'm not sure either. The next best suggestion is to pop into `#ansible` on `irc.freenode.net` and see if the gurus there have any bright ideas. – Tom O'Connor Dec 08 '14 at 10:36