Looping group_vars into a template

This is a bit over my head, so I’m going to ask.

I have several environments, with many variables defined using group_vars, e.g.

test1/group_vars/all
test2/group_vars/all

I have mule in each environment, and I need to tailor a file which tells must what libraries to load. We can it main.xml, one for each environment. Different teams should be able to include or exclude the libraries they wish to work with.

So I can’t have a global or completely static main.xml.j2 template. I do now, and I only replace a hostname, but this will not suffice.

I have to construct main.xml.

test1: main.xml might have

spring:beans
<spring:import resource=“a.xml”/>
<spring:import resource=“b.xml”/>
<spring:import resource=“c.xml”/>
<spring:import resource=“d.xml”/>
<spring:import resource=“e.xml”/>

</spring:beans>

while test2 main.xml might have

spring:beans
<spring:import resource=“a.xml”/>
<spring:import resource=“b.xml”/>
<spring:import resource=“c.xml”/>
</spring:beans>

In group_vars/all for each environment, I want
test1/group_vars/all
spring: a,b,c,d,e

test2/group_vars/all
spring: a,b,c

How should I construct my template file for this to work?

I may have some of the exact syntax wrong, I haven't as much with templates, but the following should be close.

group_vars/all:

Depending on what your results should look like you have a couple of options…

I have group_vars files for several different groups…

list_one:

  • item_a
  • item_b
  • item_c

list_two:

  • { part_one: value_one_a, part_two: value_two_a }

  • { part_one: value_one_b, part_two: value_two_b }

  • { part_one: value_one_c, part_two: value_two_c }

Then in the template files I can use

blah blah blah
{% for item in list_one %}
blah {{ item }}
{% endfor %}
blah blah blah

{% for item in list_two %}
blah {{ item.part_one }}
blah blah {{ item.part_two }}
{% endfor %}

blah blah blah

So in your case you would want to use something like this in your test1 group_vars file you would have

spring:

  • a
  • b
  • c
  • d
  • e

and your test 2 group_vars file would have
spring:

  • a
  • b
  • c

And your template would look like this…
spring:beans
{% for bean in spring %}
<spring: import resource=“{{ bean }}.xml”/>
{% endfor %}
</spring:beans>

The second example I gave at the top would be more useful if your variables have multiple related components…for example I use it for setting some information with a repeated paragraph with a server name / IP address combination in a template…

I hope that this helps.

Adam

So simple, I’m almost ashamed I asked. Thanks!