Hash and loops

17 views
Skip to first unread message

Thomas Bendler

unread,
Jan 26, 2014, 8:13:51 AM1/26/14
to puppet-users
Hi @all,

I try to pass a hash to a module class like this:

class { 'modulename':
  filecontent => {
    name1 => 'value1',
    name2 => 'value2',
    ...
    namex => 'valuex',
  }
}

​The class should take the hash list, loop over the list and create i.e. file resources with namex and content valuex. What is the best way to do this and, even more important, is it possible to do something like this?

Regards Thomas​
--
Linux ... enjoy the ride!

Jose Luis Ledesma

unread,
Jan 26, 2014, 8:49:24 AM1/26/14
to puppet...@googlegroups.com
Hello,

You should look the create_resources:

http://docs.puppetlabs.com/references/latest/function.html#createresources

Regards,

jcbollinger

unread,
Jan 27, 2014, 9:36:51 AM1/27/14
to puppet...@googlegroups.com


On Sunday, January 26, 2014 7:13:51 AM UTC-6, thbe wrote:
Hi @all,

I try to pass a hash to a module class like this:

class { 'modulename':
  filecontent => {
    name1 => 'value1',
    name2 => 'value2',
    ...
    namex => 'valuex',
  }
}

​The class should take the hash list, loop over the list and create i.e. file resources with namex and content valuex. What is the best way to do this and, even more important, is it possible to do something like this?



Yes.  You can do it in a general way (i.e. without the restrictions in form imposed by create_resources()) by relying on array-titled resources.  You also need a function to extract the keys of a hash into an array, such as the keys() function available in PuppetLabs "stdlib" add-in module.  Then you do something like this:

class modulename ($filecontent) {
  $filenames = keys($filecontent)
  modulename::file { $filenames: }
}

define modulename::file () {
  $mycontent = $modulename::filecontent[$title]
  # do something with my content
}


John

Reply all
Reply to author
Forward
0 new messages