Puppet ERB

39 views
Skip to first unread message

Sergiu Cornea

unread,
Sep 15, 2015, 4:48:02 AM9/15/15
to Puppet Users
Good morning guys,

I am trying to template the OMD rules file and for this I am using 2 arrays one which holds the IPs and the other one the Services.

In my ERB template I have this:

<% for @omd_service in @omd_service -%>
<% var1 = @omd_service %>
<% @server2.each do |omd_ip| -%>
<% end -%>
<%= var1 %> <%= omd_ip %>
<% end -%>

However, the output isn't what I am expecting:

rule1 ip1ip2

rule2 ip1ip2

Do you have an idea what I am doing wrong?

Thank you,
Sergiu

Sergiu Cornea

unread,
Sep 15, 2015, 6:12:53 AM9/15/15
to Puppet Users
The desired output will be: 

rule1 ip1
rule2 ip2

I am running Ubuntu 14.04 with Puppet 3.7

Thank you

jcbollinger

unread,
Sep 15, 2015, 9:17:14 AM9/15/15
to Puppet Users


On Tuesday, September 15, 2015 at 3:48:02 AM UTC-5, Sergiu Cornea wrote:
Good morning guys,

I am trying to template the OMD rules file and for this I am using 2 arrays one which holds the IPs and the other one the Services.

In my ERB template I have this:



This bit is surely wrong, or at least deceptive:
 
<% for @omd_service in @omd_service -%>

You must want to use a different variable for the individual services than the one containing the overall array of services.  You should not in any case be trying to assign to a variable that corresponds to a DSL variable, as DSL variables' values do not change once set.
 
<% var1 = @omd_service %>


Moreover, nesting this next loop inside the other will not produce the output you want.  It iterates through every element of array @server2 for each element of @omd_service, just as you observe.
 
<% @server2.each do |omd_ip| -%>
<% end -%>
<%= var1 %> <%= omd_ip %>
<% end -%>

However, the output isn't what I am expecting:



Perhaps not, but it's what you should expect.  Instead of a nested iteration of the two array, you want a single correlated iteration of both arrays together.  There is any number of ways to achieve that, but this one is fairly idiomatic:

<% @omd_service.zip(@server2).each do |service, server| -%>
<%= service %> <%= server %>
<% end -%>


The key here is probably the Array.zip() method.  It constructs a new array of arrays by zipping together the each set of corresponding (by index) elements of the array on which it is invoked and each of the arguments.  Each set of corresponding elements of the component arrays forms one element (an array) of the zipped result.  Iterating (singly) over that yields your pairs of corresponding elements.


John

Reply all
Reply to author
Forward
0 new messages