Puppet iteration string/array

∥☆過路亽.° 提交于 2019-12-04 19:45:38

Sadly, even if you go about and use a custom "define" to iterate over an array upon splitting your custom fact on a comma, the result will be rather not what you expect and not even close to a "for each" loop -- aside of causing you a headache, probably.

Said that, I am not sure if this is what you want to achieve, but have a look at this approach:

$fact = '1.1.1.1,2.2.2.2,3.3.3.3'

$servers = split($::fact, ',')
$count   = size($servers)

$names = bracket_expansion("host[01-${count}].address")

file { '/tmp/test.txt':
  content => inline_template('<%= @servers.each_with_index.map {|v,i| "#{v}\t\t#{@names[i]}\n" } %>'),
  ensure  => present
}

What we have there are two custom functions: size() and bracket_expansion(); which we then use values that they provide inside a hack that leverages the inline_template() function to render content of the file utilising parallel access to two arrays -- one with IP addresses from your fact and one with host names that should follow.

The result is a follows:

matti@acrux ~ $ cat | puppet apply
$fact = '1.1.1.1,2.2.2.2,3.3.3.3'

$servers = split($::fact, ',')
$count   = size($servers)

$names = bracket_expansion("host[01-${count}].address")

file { '/tmp/test.txt':
  content => inline_template('<%= @servers.each_with_index.map {|v,i| "#{v}\t\t#{@names[i]}\n" } %>'),
  ensure  => present
}
notice: /Stage[main]//File[/tmp/test.txt]/ensure: created
notice: Finished catalog run in 0.07 seconds
matti@acrux ~ $ cat /tmp/test.txt 
1.1.1.1         host01.address
2.2.2.2         host02.address
3.3.3.3         host03.address
matti@acrux ~ $

Both size() and bracket_expansion() functions can be found here:

https://github.com/kwilczynski/puppet-functions/tree/master/lib/puppet/parser/functions/

I hope this helps a little :-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!