2

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

1 Answer 1

8

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: }
2
  • Perfect, much appreciated. Just for information can I declare a variable like $num=0 and increment it for each pass of the array through the define? Or does it get reset upon each pass of define? Thanks
    – Dan
    Feb 13, 2013 at 7:40
  • @Dan Nope, that wouldn't work correctly - the declarative nature of the manifest language makes that kind of flow impossible. Feb 13, 2013 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.