Ask Your Question

$key from hash as file $value as content in file

asked 2016-10-04 13:49:42 -0500

kazein09 gravatar image

Hi all,

Im not quite sure if it`s possible to do but it will be good if someone can give me some way to how solve this. so i have output like:

$output = {"key1"=>"first value", "key2"=>"second value", "key3"=>"third value"}

I want to have on each $key file which is stored in /opt/$key.conf content with $value.

to be more clear short example : there will be 3 files
1 /opt/key1.conf with first value

2 /opt/key2.conf with second value

3 /opt/key3.conf with third value

Regards Karen

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2016-10-04 14:33:27 -0500

puser gravatar image

updated 2016-10-05 00:26:27 -0500

binford2k gravatar image

If you're running Puppet 4, this might do it for you, I didn't test it so make you you play with it:

$output.each |Integer $index, String $value| {
    file { "/opt/key${index}.conf":
        ensure  => file,
        content => $value,


edit flag offensive delete link more

answered 2016-10-05 09:22:02 -0500

Jeremiah Powell gravatar image

For Puppet 3 you can use a defined type to do this. Due to lack of looping and lack of the Puppet 4 anonymous function parameter unpacking you have to unpack the hash in two steps.

The easiest is to use the built-in $title variable on a define or class. This works with the array syntax for declaring a class or resource, like a defined type, to index into the hash.

This is how the community has faked looping for many years.

This was tested with Puppet 3.8.1.

define myfile($contents) {
  $mycontent = $contents[$title]
  file { "/path/${title}": content => $mycontent, }
$output = {
  'key1' => 'first value',
  'key2' => 'second value',
  'key3' =>'third value',
$outputkeys = keys($output)
myfile { [ $outputkeys ]: contents => $output, }

Puppetlabs-stdlib has the keys() function to get the key from a hash. You will need to require that in any module using the code.

The file resource requires a fully-qualified path, hence using "/path/${fifle}" to make this valid and apply-able Puppet 3 code.

Puppet style checks will still complain about 'the module is not in module loader format' and 'no documentation on the defined type' if you check the code.

edit flag offensive delete link more


Hi, Thanks for your comment its really works . and i can get all info as i wish. But there is one more thing also. now output is like $output = { 'key1' => { "ip" => 'first value'}, 'key2' => {"ip" => 'second value'}, 'key3' => {"ip" => 'third value'}, } how you think? is here any solution

kazein09 gravatar imagekazein09 ( 2016-10-06 17:11:38 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2016-10-04 13:49:42 -0500

Seen: 61 times

Last updated: Oct 05 '16