How to iterate over an array in Puppet

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.


As of puppet 3.2 this is possible using the "future" parser like so:

$my_env = [ 'shared1', 'shared2', 'shared3', ]
each($my_env) |$value| {
  file { "/var/tmp/$value":
    ensure => directory,
    mode => 0600,
  }
  user { $value:
    ensure -> present,
  }
}

See also: http://docs.puppetlabs.com/puppet/3/reference/lang_experimental_3_2.html#background-the-puppet-future-parser


Puppet 3.7 released earlier this month have the new DSL, which one feature is the iteration, check the following URL https://docs.puppetlabs.com/puppet/latest/reference/experiments_lambdas.html#enabling-lambdas-and-iteration

these new features can be enabled with the :

Setting parser = future in your puppet.conf file or adding the command line switch --parser=future

hope that helps

Tags:

Puppet