Posts Tagged ‘variables’

Puppet Tips&Tricks: Variable variables

Wednesday, September 1st, 2010

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'

Puppet Tips&Tricks: Variable variables

Monday, February 15th, 2010

This is the first post in a series of mine, while I’m reinventing our puppet modules. Puppet is the tool we use to maintain most machines in our care. We make it a point to share our modules as much as possible, so others might benefit from them.

Today I was working on our kbp_firewall module, which sets some variables that other modules can use via qualified variables. We differentiate between “protected”, “public” and “management” network interfaces on each host. These are always separate (virtual) interfaces, to make our life a little easier. I wanted to make both the interface and the IP address for these easily available, but I wanted most of it to happen automagically after puppet has determined which interface is connected to which network. I wanted to use the facter fact $ipaddress_(interface name), which is created for each interface, like for example $ipaddress_eth0.

Currently, there’s no way to use something like $ipaddress_${interface}, although I’ve been told on the #puppet IRC channel that this will be implemented in the next major version. So I had to create a more hackish solution. Inline_template to the rescue!

What I currently do:
$protected_ip = inline_template("<%= ipaddress_${protected_if} %>")

This will probably work in future versions too, so I feel comfortable implementing it like this. Once we’ve fully switched to the next major release, I can slowly work through the code to make it all a bit better readable.

Hope this helps someone!