Search code examples
arrayspuppetcode-duplication

How to avoid code duplication in a Puppet array?


Aim

At the company there is a script that is able to start a JAR file. Most of these JAR files need to be started twice and some of them three times. Today an array has been created in order to start JARs multiple times. It works as expected, but the question is how to avoid code duplication in a Puppet array?

Array

$variables [
  'JAR_0',
  'JAR_0',
  'JAR_0',
  'JAR_1',
  'JAR_1',
  'JAR_1',
  'JAR_2',
  'JAR_2',
  'JAR_2',
  'JAR_3',
  'JAR_3',
  'JAR_4',
  'JAR_4',
  'JAR_5',
  'JAR_5',
  'JAR_6',
  'JAR_6',
  'JAR_6',
  'JAR_7',
  'JAR_7',
  'JAR_8',
  'JAR_8',
  'JAR_8',
  'JAR_9',
  'JAR_9',
  'JAR_9'
]

For loop

<% @variables.each do |variable| -%>
    hello <%= variable %>
<% end -%>

Solution

  • You could use a map instead, like:

    $variables = {
      'JAR_0' => 3,
      'JAR_1' => 2,
      'JAR_2' => 2,
      'JAR_3' => 3
    }
    

    Then in the template you'd have a loop like this

    <% @variables.keys.each do |k| -%>
      <% @variables[k].to_i.times do -%>
        hello <%= k %>
      <% end -%>
    <% end -%>