Last Updated: September 09, 2019
·
9.304K
· firebladee

Advanced use of arrays in Puppets templates

I had a need for a variable to be optional and for it to be single or an array so had to find away for puppets template system to understand it. The below is what I came up with.

<% if !check_mk_tags.empty? %><% if check_mk_tags.is_a?(Array) %>all_hosts = all_hosts + [ "<%= hostname %>|<%= check_mk_tags.join("|") %>"]
<% else %>
all_hosts = all_hosts + [ "<%= hostname %>|<%= check_mk_tags %>"]
<% end -%>
<% else %>
all_hosts = all_hosts + [ "<%= hostname %>" ]
<% end -%>

The above first checks to see if the variable is empty, if it's not then checks to see if it is an array. If we do have an array then join it together with | in-between each variable. All of that just to get this one line:

all_hosts = all_hosts + [ "puppet01|SSH|MGMT|PROD"]

If single:

all_hosts = all_hosts + [ "puppet01|SSH"]

Or if checkmktags is empty:

all_hosts = all_hosts + [ "puppet01"]