Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 = "1.2.3.4"
}

class company::env::office {
    $dns = "2.3.4.5"
}
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

1 Answer 1

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}') %>")

Update

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)")
    end

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

    lookupvar("::company::env::#{env}::#{var}")
  end
end

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: xkcd.com/292). 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

 
discard

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.