How to iterate over an array in Puppet

PapelPincel picture PapelPincel · Oct 18, 2012 · Viewed 49.5k times · Source

I would like to iterate over an array that is stored as a Facter fact, and for each element of the array create a new system user and a directory, and finally make API calls to AWS.

Example of the fact: my_env => [shared1,shared2,shared3]

How can I iterate over an array in Puppet?

Answer

itsbruce picture itsbruce · Oct 22, 2012

This might work, depending on what you are doing

# Assuming fact my_env => [ shared1, shared2, shared3 ]

define my_resource {
  file { "/var/tmp/$name":
    ensure => directory,
    mode   => '0600',
  }
  user { $name:
    ensure => present,
  }
}
my_resource { $my_env: }

It will work if your requirements are simple, if not, Puppet makes this very hard to do. The Puppet developers have irrational prejudices against iteration based on a misunderstanding about how declarative languages work.

If this kind of resource doesn't work for you, perhaps you could give a better idea of which resource properties you are trying to set from your array?

EDIT:

With Puppet 4, this lamentable flaw was finally fixed. Current state of affairs documented here. As the documentation says, you'll find examples of the above solution in a lot of old code.