0
votes

I'm writing an Ansible role where I have some templates that must be present multiple times with different names in a single destination directory. In order not to have to handle each of these files separately I would need to be able to apply templating or some other form of placeholder substitution also to their names. To give a concrete example, I might have a file named

{{ Client }}DataSourceContext.xml

which I need to change into, say,

AcmeDataSourceContext.xml

I have many files of this kind that have to be installed in different directories, but all copies of a single file go to the same directory. If I didn't need to change their names or duplicate them I could handle a whole bunch of such files with something like

- 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'

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?

1

1 Answers

1
votes

Pretty much anywhere you can put a literal value in Ansible you can instead substitute the value of a a variable. So for example, you could do something like this:

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

This would end up creating templates /path/to/client1DataSourceContext.xml and /path/to/client2DataSourceContext.xml.

Update 1

For the question you've posed in your update:

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?

It seems like you could just do something like:

- 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'

That is, replace the string __client__ in your filenames with the value of the client_name variable.