Puppet and manifest loops

puppet

How can I access elements of an array in puppet manifests i.e. create a for/while loop? Let's say I have in my nodes.pp

Name [ 'testserver', 'floor1', 'floor3' ],

How can I iterate over that so that when I define my file resource I can iterate over each and ensure correct file resources exist for each element?

Thanks
Dan

Best Answer

There's no way to do a loop in the traditional sense, but you can probably still achieve what you're going for. An array, when used as a resource title, will be automatically expanded.

So for a simple case, you'd just have an array like

$packages = [ 'httpd', 'mysql', 'puppet' ]

Then use that in a resource, like:

package { $packages:
  ensure => installed,
}

For more complicated cases, you can use a defined type. I'm not quite sure where you're going with your example - let me know if this doesn't make sense for your use case.

Say, for instance, you're sending in an array of [ 'testserver', 'floor1', 'floor3' ] and what you're needing to do with that list is to create a file at /etc/foo/testserver (for the first element), then run an exec to set something up once that's done.

define datafiles {
  file { "/etc/foo/${title}":
    ensure  => present,
    content => $title,
  }
  exec { "setup-${title}":
    command => "/usr/local/bin/something -a /etc/foo/${title}",
    require => File["/etc/foo/${title}"],
  }
}

Then, using the array in the title of the defined type will expand it, creating both the file and exec resources for each member of the array.

$names = [ 'testserver', 'floor1', 'floor3' ]
datafiles { $names: }