Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to dynamically access a variable in a class? For example:

class namespace::hello() {
    $cow = "moo"
    $dog = "bark"

$dynamic = 'cow'
$value = $namespace::hello::[$dynamic]  # doesn't work

I'm doing this because I have classes defined with variables in them for each environment, e.g.:

class company::env::production {
    $dns = ""

class company::env::office {
    $dns = ""
share|improve this question
So, you're trying to dynamically reference either company::env::production or company::env::office based on which environment the node is in? I'd like to understand a little more of what you're trying to do with this, but I don't think this kind of class structure is a good solution. – Shane Madden Jan 6 '13 at 6:04
@ShaneMadden Yes, basically. Throughout the code I would like to access the environment settings, i.e. the $dns variable, depending on what the node is declared as. What alternatives would you suggest? – Gerald Kaszuba Jan 6 '13 at 6:25
It could be as simple as just doing a case check against the dynamic variable ($environment?) to set the $dns variable instead of putting them in different classes. But as Ger mentioned in your answer below, using Hiera is probably your best option if you have the ability to switch over to using it. – Shane Madden Jan 6 '13 at 6:56
up vote 2 down vote accepted

I have found a nasty solution. I hope someone can give me a better alternative.

By using inline_template with scope.lookupvar, you can reference a dynamic variable:

inline_template("<%= scope.lookupvar('$namespace::hello::${dynamic}') %>")


Because of the complexity of the solution, I just made a hack on top of that hack. I made a custom function that's does that one liner:

module Puppet::Parser::Functions
  newfunction(:config, :type => :rvalue) do |arguments|

    if arguments.size != 2
      raise(Puppet::ParseError, "config(): 2 args required)")

    env = arguments[0]
    var = arguments[1]


And in your .pp:

$dns_server = config("production", "dns_server")
share|improve this answer
You desperately need Hiera, although this hack might fix your problem now, it will haunt you sometime in the future... – Ger Apeldoorn Jan 6 '13 at 6:52
@GerApeldoorn Yes, I am definitely worried about raptors (reference: Thanks, I will check out hiera. – Gerald Kaszuba Jan 6 '13 at 6:58
That xkcd is awesome, thanks! :-) – Ger Apeldoorn Jan 7 '13 at 5:47

Your Answer


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.