Puppet Foreach / For Loop Workaround

Here is a quick workaround to effectively write a foreach loop in puppet. There isn’t a native foreach function that I’m aware of, however it is possible to obtain similar functionality by using a define statement.

Let’s create a simple example to loop over multiple users, and perform an action on each user. In this case we’ll print “Found user ” for each user.

$users = [ "user1", "user2" ]
 
define print_users {
        $user = $name
        notify { "Found user $user":; }
}
 
print_users { $users:; }

On the agent we should see output that looks like this:

notice: /Stage[main]/Test/Test::Print_users[user1]/Notify[Found user user1]/message: current_value absent, should be Found user user1 (noop)
notice: Test::Print_users[user1]: Would have triggered 'refresh' from 1 events
notice: /Stage[main]/Test/Test::Print_users[user2]/Notify[Found user user2]/message: current_value absent, should be Found user user2 (noop)
notice: Test::Print_users[user2]: Would have triggered 'refresh' from 1 events
notice: Class[Test]: Would have triggered 'refresh' from 2 events

So, as you can see, this effectively allows us to loop through the elements in an array and perform actions in a way that is very similar to a foreach loop.

Thanks to https://blog.kumina.nl/tag/puppet-tips-and-tricks/ for documenting this tip.