Ansible:可定制的模板文件名

Ansible: customizable template filenames

我正在编写一个 Ansible 角色,其中我有一些模板必须在单个目标目录中以不同的名称多次出现。为了不必单独处理这些文件中的每一个,我需要能够对它们的名称应用模板或其他形式的占位符替换。举一个具体的例子,我可能有一个名为

的文件
{{ Client }}DataSourceContext.xml

我需要改成,比方说,

AcmeDataSourceContext.xml

我有许多此类文件必须安装在不同的目录中,但单个文件的所有副本都位于同一目录中。如果我不需要更改它们的名称或复制它们,我可以用

之类的东西处理一大堆这样的文件
- name: Process a whole subtree of templates
  template:
    src: "{{ item.src }}"
    dest: "/path/to/{{ item.path }}"
  with_filetree: ../templates/my-templates/
  when: item.state == 'file'

我想我想要的是一个神奇的 consider_filenames_as_templates 开关,它可以打开文件名预处理。有什么方法可以模拟这种行为吗?

在 Ansible 中几乎任何可以放置文字值的地方,您都可以用变量的值代替。例如,您可以这样做:

- template:
    src: sometemplate.xml
    dest: "/path/to/{{ item }}DataSourceContext.xml"
  loop:
    - client1
    - client2

这最终会创建模板 /path/to/client1DataSourceContext.xml/path/to/client2DataSourceContext.xml.

更新 1

对于您在更新中提出的问题:

I guess what I'd like is a magic consider_filenames_as_templates toggle that turned on filename preprocessing. Is there any way to approximate this behaviour?

看来你可以做类似的事情:

- name: Process a whole subtree of templates
  template:
    src: "{{ item.src }}"
    dest: "/path/to/{{ item.path.replace('__client__', client_name) }}"
  with_filetree: ../templates/my-templates/
  when: item.state == 'file'

也就是说,将文件名中的字符串 __client__ 替换为 client_name 变量的值。