I’m looking for an easy way to add public keys to the authorized_keys file, if the key for the user is present in a specific directory. Right now it throws an error if the public key doesn’t exist.
I want to create users on systems and push their public keys. For that, I am using the authorized_key module:
- name: Add pubkeys
ansible.posix.authorized_key:
user: "{{ item.username }}"
state: present
key: "{{ lookup('file', '~/ap/ansible/sonderfiles/{{ item.username }}_pubkey.pub') }}"
loop: "{{ userlist }}"
I found threads mentioning the module stat but I cant figure out a way to iterate through a list of files and use the results in a when condition in the authorized_key module.
>Solution :
This can be achieve with a condition and an is file test.
This said, there is a little trick to it, like in maths, some operators are taking precedence on others, and in this case, the is operator of the test is taking precedent on the concatenation operator ~.
So, the trick is to put the concatenated path in parenthesis:
- name: Add pubkeys
ansible.posix.authorized_key:
user: "{{ item.username }}"
state: present
key: >-
{{ lookup(
'file',
'~/ap/ansible/sonderfiles/' ~ item.username ~ '_pubkey.pub'
) }}
loop: "{{ userlist }}"
when: "('~/ap/ansible/sonderfiles/' ~ item.username ~ '_pubkey.pub') is file"