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
notice: //Do_this[eth0]/Notify[Found interface]/message: defined 'message' as 'Found interface'
notice: Found interface
notice: //Do_this[eth1]/Notify[Found interface]/message: defined 'message' as 'Found interface'

Tags: , , , , , , ,

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

  1. Thomas says:

    All it does for me is printing out the internface name, but not the IP address. Do I miss anything?

    Notice: ipaddress_ens192
    Notice: /Stage[main]/Main/Node[localhost]/Do_this[ens192]/Notify[ipaddress_ens192]/message: defined ‘message’ as ‘ipaddress_ens192’
    Notice: ipaddress_ens224
    Notice: /Stage[main]/Main/Node[localhost]/Do_this[ens224]/Notify[ipaddress_ens224]/message: defined ‘message’ as ‘ipaddress_ens224’

    • Kumina bv says:

      It works for us with Puppet 3.8.7, although you should run ‘puppet apply net.pp’. That is the only Puppet version we use at the moment so I can’t test it on a different one.

  2. cognoscentis says:

    thank you, thank you, thank you!

  3. rdark says:

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

  4. 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.

  5. 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.

Kumina designs, builds, operates and supports Kubernetes solutions that help companies thrive online. As Certified Kubernetes Service Partner, we know how to build real solutions.