Ruby/ERB cheat sheet for puppet users not familiar with Ruby in general

puppetruby

I'm still getting to grips with puppet and starting to mess around with templating, which is based on Ruby's ERB system. I am not familiar with Ruby in general, does anyone know of a cheat sheet for ERB or will I need to get my hands dirty and learn some Ruby basics?

Best Answer

I was in the exact same situation some time back. Basically, for erb templates to be used by puppet, you do not require much knowledge of Ruby. But, that also depends on the complexity and purpose of your puppet modules.

If for example, you are mainly going to use them for configuration files for server management, then mostly you'd be needing to manipulate things as ip addresses and hostnames. And the most commonly used Ruby functions you'd be encountering are split and join.

The easiest way to mess around with these and other functions would be to install ruby and its interactive shell, irb and test your code. So...a cheat sheet, I don't know. I bugged folks over at stack overflow and #ruby on irc ! I have a bunch of templates here https://github.com/alcy/pupmods/tree/master/puppet/templates/ ( badly organized ! ), that might help you.

Regarding the case statement query, you can have something like this ( one of the possible approaches ) :

$ip1=inline_template('<%= ipaddress.split(".")[0..2].collect{|x| x}.join(".") %>')

$source = $ip1 ? {
  "10.0.0" => "puppet:///your-module-name/resolv.conf.1",
  "10.0.1" => "puppet:///your-module-name/resolv.conf.2",
  }

file {"/etc/resolv.conf":
  ensure => present,
  source => $source,
  }

The template part of it is explained as: split the ipaddress of the client machine obtained from facter at each occurrence of a DOT ".", collect the first three numbers, and join them with a DOT in between each element. Store this as variable ip1. According to this value, serve the necessary resolv.conf file from puppet's file server.