Search code examples
scopepuppet

Puppet 2.7: Updating hash in the parent scope fails


I need to recursively insert entries in a hash based on some logic. The state of the hash gets updated inside the defined type loop, but not in the outer scope. The following should clarify:

class Test {
  $config = {}
  define my_loop()
  {
     $config['a'] = 'b'
     notify { "1) config = $config": } # shows that $config has a=>b
  }

  my_loop { 'loop' : }
  notify { "2) config = $config":
    require => My_loop['loop'] # shows that $config is empty
  }
}

So, the problem is that $config inside the loop() contains a=>b, but outside the loop() it doesn't. I must be bumping against some scoping rules here.

Thoughts?


Solution

  • The values of Puppet variables are set once, and they do not change thereafter. In those few places that present the appearance of behaving differently, what actually happens is either that a modified local copy or an entirely independent variable is created.

    Additionally, do not nest classes or defined types inside classes. Puppet allows it for historical reasons, but it doesn't have the semantics you probably expect, and it makes the nested class / type hard to find.

    Consider writing a custom function to perform your computation and return the needed hash.

    Also consider whether upgrading to a supported version of Puppet would be feasible. Version 2.7 is very old.