puppet hash iteration – Replacing create_resources() with Hash Iteration in Puppet

configuration-managementpuppetruby

We're migrating from Puppet 2 to 5. It seems the scoping is a little different. Before, when using create_resources() with a hiera_hash and a default hash, variables from within the calling script were available to the ERB, but now they don't seem to be. For example, I could set $a = 'hello world' in the calling script right before create_resources(), and then within my ERB, I could simply reference $a and get back hello world. That doesn't seem to be the case now.

So the idea is to abandon create_resources() and use Puppet 5's each function on the hiera_hash just creating a new file within the loop. However, I'm having trouble merging the default values to each hash element. I'm not able to redeclare variables, so I can't do a merge within the loop it seems.

Here's an example of what I'm trying to do:

Data.file1.yaml

my::data:
  element_a:
    fname: 'Brian'
    lname: 'Detweiler'
  element_b:
    fname: 'Joe'
    lname: 'Schmoe'

Data.default.yaml

my::defaults
  mname: 'M.'

Before I would pull both of those in as hiera_hashs and do create_resources('my::template::script', $names, $names_default) and I would end up with the expected merges:

'element_a' => { fname => 'Brian', lname => 'Detweiler', mname => 'M.'},
'element_b' => { fname => 'Joe', lname => 'Schmoe', mname => 'M.'}

Now I want to do

$names.each | String $key, Hash $value | {
  $merged_hash_val = $names_default + $value
  file {
    # ... create file with $merged_hash_val in here
  }
}

But since variables are immutable, I can't reassign values. Is there a way around this?

Best Answer

Variables are still accessible to the template. I am concerned that there is something else going on there. You might not want to change your create_resources() usage if you address that.

See: https://puppet.com/docs/puppet/5.5/lang_template_erb.html#accessing-puppet-variables