Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 7 down vote accepted

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: }
share|improve this answer
    
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 '13 at 7:40
    
@Dan Nope, that wouldn't work correctly - the declarative nature of the manifest language makes that kind of flow impossible. –  Shane Madden Feb 13 '13 at 20:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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