Achieving a for loop in Puppet (4.10.x)
I was working on a module that installed a package. I wanted to take the systemd unit file that was installed through this process and pass in a parameter into the puppet class, to specify a number representing the number of extra of this service I wanted running.
Here is the original module:
After a fair bit of research, I discovered Puppet doesn’t have a native for
loop but it does have the range
function. Interestingly, range
doesn’t support integers so you need to pass in strings.
So, firstly I added a parameter to pass in the agent count, defaulting it to 1:
Then add some conditional logic to check if $agent_count
is >
than 1, if it is, we use the range
function to iterate from 2
to x
, x
being the value of $agent_count
:
All things going well, you should see something like this in your puppet output when you apply it:
==> buildkite: Notice: /Stage[main]/Buildkite::Install/File[/usr/lib/systemd/system/buildkite-agent2.service]/ensure: defined content as '{md5}edbc4acd44578ec59c6e72f463d96e33'==> buildkite: Notice: /Stage[main]/Buildkite::Install/File[/usr/lib/systemd/system/buildkite-agent3.service]/ensure: defined content as '{md5}edbc4acd44578ec59c6e72f463d96e33'==> buildkite: Notice: /Stage[main]/Buildkite::Install/File[/usr/lib/systemd/system/buildkite-agent4.service]/ensure: defined content as '{md5}edbc4acd44578ec59c6e72f463d96e33'==> buildkite: Notice: /Stage[main]/Buildkite::Install/File[/usr/lib/systemd/system/buildkite-agent5.service]/ensure: defined content as '{md5}edbc4acd44578ec59c6e72f463d96e33'
The lesson learnt here for me is to always check the stdlib of what ever language you are working with, Puppet’s stdlib documentation lives here https://forge.puppet.com/puppetlabs/stdlib.
I hope this was helpful. :)