There are a couple of steps to prepare this functionality. First, get the value of the parameter. There might be more options, e.g. by default
shell> sudo sshd -T | grep authorizedkeysfile
authorizedkeysfile .ssh/authorized_keys .ssh/authorized_keys2
For example, get the first one
- shell: sshd -T | grep authorizedkeysfile
register: result
become: true
- set_fact:
AuthorizedKeysFile: "{{ (result.stdout|split)[1] }}"
gives
AuthorizedKeysFile: .ssh/authorized_keys
The parameter AuthorizedKeysFile may contain %u
and %h
. See Location of the Authorized Keys File
%h will be replaced by the home directory of the user being authenticated, and %u by the login name of the user
Prepare the database of the home directories
- getent:
database: passwd
By default, the module getent stores the database passwd in the dictionary getent_passwd. Home is the 4th attribute, e.g.
- debug:
var: getent_passwd['root'][4]
gives
getent_passwd['root'][4]: /root
Now, given the data
auth_keys:
root: [key1, key2, key3]
you can test the functionality
- shell: sshd -T | grep authorizedkeysfile
register: result
become: true
- set_fact:
AuthorizedKeysFile: "{{ (result.stdout|split)[1] }}"
- getent:
database: passwd
- debug:
msg: |
path: {{ _path }}
keys: {{ item.value }}
loop: "{{ auth_keys|dict2items }}"
vars:
_user: "{{ item.key }}"
_home: "{{ getent_passwd[item.key][4] }}"
_akf: "{{ AuthorizedKeysFile|regex_replace('%u', _user)|
regex_replace('%h', _home) }}"
_path: "{{ (_akf.0 == '/')|ternary(_akf, [_home, _akf]|join('/')) }}"
gives
msg: |-
path: /root/.ssh/authorized_keys
keys: ['key1', 'key2', 'key3']
If you change the parameter
shell> sudo sshd -T | grep authorizedkeysfile
authorizedkeysfile /etc/ssh/authorized_keys/%u
the play will get the correct location of the authorized keys file
msg: |-
path: /etc/ssh/authorized_keys/root
keys: ['key1', 'key2', 'key3']