Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 694
Naftuli Kay Avatar asked Jan 25 '17 03:01

Naftuli Kay


1 Answers

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.

like image 73
techraf Avatar answered Oct 19 '22 13:10

techraf