Using ERB templates
While you can deploy config files easily with Puppet as simple text files, templates are much more powerful. A template file can do calculations, execute Ruby code, or reference the values of variables from your Puppet manifests. Anywhere you might deploy a text file using Puppet, you can use a template instead.
In the simplest case, a template can just be a static text file. More usefully, you can insert variables into it using the ERB (embedded Ruby) syntax. For example:
<%= @name %>, this is a very large drink.
If the template is used in a context where the variable $name
contains Zaphod Beeblebrox
, the template will evaluate to:
Zaphod Beeblebrox, this is a very large drink.
This simple technique is very useful to generate lots of files that only differ in the values of one or two variables, for example, virtual hosts, and for inserting values into a script such as database names and passwords.
How to do it…
In this example, we'll use an ERB template to insert a password into a backup script:
- Create the file
modules/admin/templates/backup-mysql.sh.erb
with the following contents:#!/bin/sh /usr/bin/mysqldump -uroot \ -p<%= @mysql_password %> \ --all-databases | \ /bin/gzip > /backup/mysql/all-databases.sql.gz
- Modify your
site.pp
file as follows:node 'cookbook' { $mysql_password = 'secret' file { '/usr/local/bin/backup-mysql': content => template('admin/backup-mysql.sh.erb'), mode => '0755', } }
- Run Puppet:
[root@cookbook ~]# puppet agent -t Info: Caching catalog for cookbook.example.com Info: Applying configuration version '1412140971' Notice: /Stage[main]/Main/Node[cookbook]/File[/usr/local/bin/backup-mysql]/ensure: defined content as '{md5}c12af56559ef36529975d568ff52dca5' Notice: Finished catalog run in 0.31 seconds
- Check whether Puppet has correctly inserted the password into the template:
[root@cookbook ~]# cat /usr/local/bin/backup-mysql #!/bin/sh /usr/bin/mysqldump -uroot \ -psecret \ --all-databases | \ /bin/gzip > /backup/mysql/all-databases.sql.gz
How it works…
Wherever a variable is referenced in the template, for example <%= @mysql_password %>
, Puppet will replace it with the corresponding value, secret
.
There's more…
In the example, we only used one variable in the template, but you can have as many as you like. These can also be facts:
ServerName <%= @fqdn %>
Or Ruby expressions:
MAILTO=<%= @emails.join(',') %>
Or any Ruby code you want:
ServerAdmin <%= @sitedomain == 'coldcomfort.com' ? 'seth@coldcomfort.com' : 'flora@poste.com' %>
See also
- The Using GnuPG to encrypt secrets recipe in this chapter
- https://docs.puppetlabs.com/guides/templating.html