Reputation: 4879
Ansible gurus I need your help. I have a template with a variable I need to set dynamically while iterating through a list in the playbook. It's not clear how to "inject" a variable to the template to use while iterating.
Objective is to create many config files in a directory, one for each var in a list. For example if the list is A, B, C
I would want files A.conf, B.conf, C.conf respectively.
Within the template config file, there is a variable that needs to be set with the A, B, or C respectively as well. I tried to use the set_fact
and set variable from the list item and reference. I tried to reference {{ item }}
within. All failed?
apps:
- one
- two
- three
tasks:
- name: Install Logstash config
template: src={{ upload_dir }}/deploy/logstash-etl.conf dest=/opt/logstash/bin/etl-{{ item }}.conf
set_fact:
app: "{{ item }}"
delegate_to: "{{ logstash_host }}"
with_items: apps
Within the template file I've tried to reference {{ app }}
and {{ item }}
and I cannot seem to get it to recognize the dynamic variable to set it's value from the current value of the iteration.
Expected if I had apps: one, two, three would be 3 files in a folder each named etl-one.conf, etl-two.conf, etl-three.conf respectively and within each file a variable in the config dynamically set like "topic_id": "etl.one.Event" for etl-one.conf and "topic_id": "etl.two.Event" for etl-two.conf respectively.
Many thanks for any ideas. The set_fact
was my latest attempt and that fails with a
ERROR: multiple actions specified in task: 'template' and 'Install Logstash config'
exit status 1
Upvotes: 5
Views: 5972
Reputation: 4879
I got it to work without errors. It appears the template CAN reference the {{ item }}
variable as you iterate so you use it within the template.
- name: Install Logstash config
template: src={{ upload_dir }}/deploy/logstash-etl.conf dest=/opt/logstash/bin/etl-{{ item }}.conf
delegate_to: "{{ logstash_host }}"
with_items: apps
And in template file:
"topic_id": "etl.{{ item }}.Event"
Upvotes: 6