What is the best way in Puppet to add a piece of text to the /etc/hosts file?

I would also like to keep the ability to manually edit hosts-file, at least the first 10 lines.

#Public IP's - eth0
192.168.1.103   front-01
192.168.1.106   front-02

#Private IP's - eth1
192.169.40.201  priv0-0
192.169.40.202  priv0-1
192.169.40.207  priv1-0
192.169.40.208  priv1-1

#Virtual IP's - eth0:1
192.169.50.202  vip-01
192.169.50.205  vip-02

Having these hosts entries at the bottom of the /etc/hosts, would be perfect. What is the best way to do this? Is there a better way than writing 8 hosts-lines manifest?

# create a simple hostname and ip host entry
host { 'front-01':
    ip => '192.168.1.103',
}

There might be server groups that need different IP's /hostnames in their /etc/hosts. I would use a template, but that means people can no longer make manual changes in their /etc/hosts as they would get overwritten by the template.


Solution 1:

Honestly, using the host resource is the simplest way to do this. You only have to define the hosts you want controlled by puppet, and you can still edit the rest of the file by hand (even though Puppet drops in that header that tells you not to).

The augeas module is overkill for a hosts file, because it just duplicates the functionality of the host resource (although it doesn't add in the "don't edit this file" header).

If you really want something more complicated or you want fine control over the placement of lines in the file, use the concat module with a local source for one of the fragments. There's an example for just that sort of thing (using the motd file) in the concat documentation.

But really, just use the host resource for the hosts you want to define from Puppet and edit the local hosts files for anything else you need.

Also note that you can write the host definitions pretty compactly in Puppet:

host {
  # Public IPs - eth0
  'front-01': ip => '192.168.1.103';
  'front-02': ip => '192.168.1.106';

  # Private IPs - eth1
  'priv0-0': ip => '192.169.40.201';
  'priv0-1': ip => '192.169.40.202';
  'priv1-0': ip => '192.169.40.207';
  'priv1-1': ip => '192.169.40.208';

  # Virtual IPs - eth0:1
  'vip-01': ip => '192.169.50.202';
  'vip-02': ip => '192.169.50.205';
}

Solution 2:

Use the augeaus functionality built into puppet. You want something like

augeas {
  context => "files/etc/hosts"
  changes => [
    "set <ip address> <name>",
  ],
}