Looping through a Template

27 views
Skip to first unread message

Jeffrey Ward

unread,
Apr 11, 2017, 8:59:54 AM4/11/17
to Ansible Project
Hi,


I am new to ansible and new to the form.

I am wondering how to loop through a template

my template looks like this


{ item.sitename  }}-test,{{ item.sitename  }} description

 and my variables look like this

---
parameters:
  - { sitename: testsite1  }
  - { sitename: testsite2  }

my Task looks like this

---
- name: Lines Templates
  template: src=test.j2 dest=../ansible/configurations/test.csv
  with_items: "{{ parameters }}"

this works but I only get the one line of the last entry  with looks like this

testsite2-test,testsite2 description


But what I am tring to get is this


testsite1-test,testsite1 description
testsite2-test,testsite2 description


I have been looking and reading the Jinga2 Templates doc but truble finding which {% for in %} to use

if some one could point me to the right direction that would be great.


Jeff








J Hawkesworth

unread,
Apr 11, 2017, 12:36:01 PM4/11/17
to Ansible Project
Hi,

I think you are almost there.

You almost certainly don't want to have 'with_items' on your template call.  This will try to template once for each item in "{{parameters}}".  But "{{parameters}}" is already a list of things, and is going to be available to use in the template as a list, so I think you just need to make your template like this

{% item for in parameters %}
{ item.sitename  }}-test,{{ item.sitename  }} description
{% endfor %}

That should loop through "{{parameters}}" and put each templated item onto a new line I think (not tested).

Hope this helps,

Jon

Jeffrey Ward

unread,
Apr 11, 2017, 2:06:08 PM4/11/17
to Ansible Project
Jon I actually got it with this

{% for myitem in item.sitename|list %} 

I left my Task the same with with items but changed my VAR to an array

---
parameters:
  - {sitename: ['site1', 'site2', 'site3', 'site4'] }


Thanks for you help
Reply all
Reply to author
Forward
0 new messages