puppet loops

Puppet is automation software for IT system admins, consultants, etc. It allows you to automate repetitive tasks such as the installation of applications and services, patch management, and deployments. but it has many bottlenecks when it comes to doing some standalone deployments. puppet doesn't have native support for loops so we will have to follow a workaround in order to create a loop.


Following is a for loop where we can parse the loop starting value and the max count to the loop.

Example:

class loop_test {

  #Invoking the loop resource name is the loop starting point.

  loop{"1":

    count=>"5", # Loop ending index

  }

}

define loop($count) {

  if ($name > $count) {

    notice("Loop Iteration Finished!!!\n")

  }

  else

  {

    notice("The Iteration Number : $name \n")

    $next = $name + 1

    loop { $next:

      count => "${count}",

    }

  }

}

include loop_test


Now let's see how can we have a nested loop in this loop. There are two ways you can do this, one is simply iterating over an array or define another resource that you can recursively call.

The following code segment can be used to achieve this.

class loop_test {

  #Invoking the loop resource name is the loop starting point.

  loop{"1":

    count=>"5", # Loop ending index

  }

  $config_array = ["Value 01","Value 02","Value 03","Value 04","Value 05"]

}

define loop($count) {

  if ($name > $count) {

    notice("Loop Iteration Finished!!!\n")

  }

  else

  {

    notice("The Iteration Number : $name \n")

    # This is to avoid any resource name duplications

    $local_names = regsubst($loop_test::config_array, '$', "-$name")

    # Invoking the second iteration

    push_templates{$local_names:

      loop_index => $name,

    }

    $next = $name + 1

    loop { $next:

      count => "${count}",

    }

  }

}

define push_templates($loop_index) {

  $orig_name = regsubst($name, '-[0-9]+$', '') # Extract the Original name

  # Do something Here

  notice("The Loop Index : ${loop_index} \n The Array Content : $orig_name \n")

}

include loop_test

Github repo for:https://github.com/zippyopstraining/puppetloops




Relevant Blogs:

Ansible Modules

Ordering puppet resources with run stages 

Puppet module automation 

OpenVAS Installation and configuration

Recent Comments

No comments

Leave a Comment