I have a fairly simple playbook which creates authorized_keys
entries for a given user in Ansible:
- name: chat user authorized keys
authorized_key:
user: chat
key: |
{% for filename in lookup('fileglob', 'public_keys/*.pub') %}
# {{ filename }}
{{ lookup('file', filename ) }}
{% endfor %}
exclusive: true
I have around six public key files in that directory. I'm trying to format a single file content with all of the keys delimited by newlines.
This is what is suggested by the Ansible docs:
exclusive
Whether to remove all other non-specified keys from the authorized_keys file. Multiple keys can be specified in a single key string value by separating them by newlines. This option is not loop aware, so if you use
with_
, it will be exclusive per iteration of the loop, if you want multiple keys in the file you need to pass them all tokey
in a single batch as mentioned above.
How can I use a fileglob to concatenate all of the files matching public_keys/*.pub
into a single key here so that I can maintain exclusivity and properly remove keys when necessary?
This will concatenate multiple files separating their contents by newline characters:
{% for filename in lookup('fileglob', 'public_keys/*.pub', wantlist=true) -%}
{{ lookup('file', filename) }}
{% endfor %}
With the default Ansible/Jinja2 settings, the output will be separated by exactly one newline character regardless if the *.pub
files end with a trailing line or not.
-%}
in the first expression prevents a space character being added at the beginning of each line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With