How to concatenate files with a glob pattern as a single value?
Asked Answered
K

1

6

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 to key 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?

Kho answered 25/1, 2017 at 3:23 Comment(0)
I
10

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.

Interrelation answered 25/1, 2017 at 4:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.