Wednesday, January 9, 2013

Puppet Template : Loop with multiple variables


Is @path supposed to be the same for each user? If so, you can just put that variable in the block.
<% @users.each do |user| %>
    /bin/mount --bind <%= @path %> /home/<%= user %>
<% end %>

If each user has a path value unique to them, following are some ways to achieve it.

Solution1 : 
(in Puppet class)
$mountpoints = { 
      'user1' => '/home/some/path', 
      'user2' => /home/another/path'
}
(in Puppet template)
<% mountpoints.each do |user, path| -%>
/bin/mount --bind <%= path %> /home/<%= user %>/www 
<% end -%>

Solution2 :  you might want to put that in an array of hashes and then iterate over that like this:

(in Puppet class)
$users = [ { name => 'alice', path => '/alice/path' }, 
           { name => 'bob', path => '/bob/path' } ]
(in Puppet template)
<% @users.each do |user| %>
    /bin/mount --bind <%= user['path'] %> /home/<%= user['name'] %>
<% end %>


Defining custom function to generate Array of Hash

Function  :
test-module/lib/puppet/parser/functions/produceArray.rb
module Puppet::Parser::Functions
    newfunction(:producearray, :type => :rvalue) do |args|  

        serverArray  = args[0].split(",")
        propArray    = args[1].split(",")

        myarray = []
        serverArray.each do |obj|
            i  = 0
            myServer = Hash.new
            obj.split(":").each do |prop|
                myServer[propArray[i]] = prop
                i = i+1
            end
            myarray.push(myServer)
        end
        return myarray
    end

end


Manifest :
test-module/manifests/init.pp
$serverlist1  = producearray("10.176.40.171:8080,10.183.32.157:8081","ip,port")
$serverlist2  = producearray("10.176.40.171:8080:password1,10.183.32.157:8081:password2","ip,port,password")

file {'/usr/local/templateOutput' :
    ensure => present,
    content => template("test-module/template.erb"), 
}

Template :
test-module/templates/template.erb

<% for @server in @serverlist1 %>
{
    Ldap Ip : <%= @server['ip'] %> 
    Ldap Port :<%= @server['port'] %>
}
<% end %>
.................
<% for @server in @serverlist2 %>
{
    Ldap Ip : <%= @server['ip'] %> 
    Ldap Port :<%= @server['port'] %>
    Ldap password :<%= @server['password'] %>
}
<% end %>


Output :
/usr/local/templateOutput
{
        Ldap Ip : 10.176.40.171
        Ldap Port :8080
}
{
        Ldap Ip : 10.183.32.157
        Ldap Port :8081
}
.................
{
        Ldap Ip : 10.176.40.171
        Ldap Port :8080
        Ldap password :password1
}
{
        Ldap Ip : 10.183.32.157
        Ldap Port :8081
        Ldap password :password2
}

No comments:

Post a Comment