Puppet Tips&Tricks: Variable variables

Sometimes you want to use variable variables, for instance when you want to iterate over all the ipaddress_* facts that facter found. Using something like ${ipaddress_$if} doesn’t work, though. Inline_template to the rescue! Thanks to Volcane on IRC, this is a possible solution:

$ifs = split($interfaces,",")

define do_this {
	$mule = "ipaddress_${name}"
	$donkey = inline_template("<%= scope.lookupvar(mule) %>")

	notify { "Found interface $donkey":; }
}

do_this { $ifs:; }

This will output:

$ sudo puppet net.pp 
notice: Found interface 172.29.121.22
notice: //Do_this[eth0]/Notify[Found interface 172.29.121.22]/message: defined 'message' as 'Found interface 172.29.121.22'
notice: Found interface 213.207.83.56
notice: //Do_this[eth1]/Notify[Found interface 213.207.83.56]/message: defined 'message' as 'Found interface 213.207.83.56'

Tags: , , , , , , ,


5 Responses to “Puppet Tips&Tricks: Variable variables”

  1. […] it was still annoying nonetheless so I was pleasantly surprised when a friend pointed me towards this blog entry which offered a possible solution, you use Puppets inline_template function to evaluate a small ERB […]

  2. Stefan says:

    Thanks a lot! I spent hours to try to find the right syntax. Love the “Google God” which brought me to your really helpful blog.

  3. James Legg says:

    Thanks for this, feel like over two years after you wrote this something better should be available in puppet, but as of yet I haven’t found it.

  4. rdark says:

    There’s also the ‘getvar’ function as part of stdlib that can do the same thing, but tidier – $newvar = getvar(“ipaddress_${name}”)

  5. cognoscentis says:

    thank you, thank you, thank you!

Leave a Reply