如何将具有 glob 模式的文件连接为单个值?

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

我有一个相当简单的剧本,它在 Ansible 中为给定用户创建 authorized_keys 条目:

 - 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

我在该目录中有大约六个 public 关键文件。我正在尝试使用换行符分隔的所有键来格式化单个文件内容。

这是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.

我如何使用 fileglob 将匹配 public_keys/*.pub 的所有文件连接到一个键中,以便我可以保持排他性并在必要时正确删除键?

这将连接多个文件,用换行符分隔它们的内容:

{% for filename in lookup('fileglob', 'public_keys/*.pub', wantlist=true) -%}
{{ lookup('file', filename) }}

{% endfor %}

使用默认 Ansible/Jinja2 设置,无论 *.pub 文件是否以尾行结尾,输出都将由一个换行符分隔。

第一个表达式中的

-%} 阻止在每行的开头添加 space 字符。