Puppet – How to Iterate Resources in a Puppet Template

puppet

I am trying to manage my /etc/hosts file with puppet, but I don't like the internal 'host' type, I'd like to use my own template if possible.

I have therefore defined a 'host' resource:

    # Basic hosts configuration
    class hosts {

    # Host resource
    define host (
        $address,
        $names
    ) {

    }

    Network::Hosts::Host {
        before   => File['/etc/hosts']
    }

    # Configure hosts file
    file {
        "/etc/hosts":
        ensure   => present,
        checksum => md5,
        owner    => root,
        group    => root,
        mode     => 0644,
        content  => template("network/hosts.erb"),
    }

In other places, I define host resources:

network::hosts::host { 'puppet.test.lan':
    address => '192.168.56.101',
    names => 'puppet',
}

I would like to include the list of the defined hosts in my template, but I don't know how to iterate over the resources and their properties. I tried using string concatenation, but couldn't make it work and was not very elegant.

How can I iterate over all my defined hosts and include them from the template?

Best Answer

You could use R.I.Pienaar's puppet-concat module where you build a single file out of many smaller files or templates.

The define would then look something like this:

define host($address, $names) {
  concat::fragment{"hosts-$address":
    target  => "/etc/hosts",
    content => template("network/hosts_single.erb")
  }
}

The hosts_single.erb template would represent a single line in the file. You'd probably also add a fragment for a header too and set order => "01" to ensure it's at the top of the generated file (10 is the default).

Related Topic