If you manage hosts in Ansible, and you also use nagios to monitor those hosts, you might be looking for ways to keep your config DRY.

With Ansible templates, this is easy!

Let’s say your inventory file for your hosts looks something like this:

[dev3]
dev3.lab ansible_host=192.168.1.111

[dev4]
dev4.lab ansible_host=192.168.1.112

And let’s also say that these hosts belong to certain nagios hostgroups

Then we might use Ansible host groups to automatically assign the Ansible managed hosts to the proper nagios hostgroups. So we add to our inventory file:

[nagios-hostgroup-dev-servers:children]
dev3
dev4

[nagios-hostgroup-dev-dbs:children]
dev3

So then our Ansible task can look like this:

    - template:
        src: templates/ansible-managed-nagios-hosts.j2
        dest: /usr/local/nagios/etc/servers/ansible-managed-nagios-hosts.cfg
      become: yes

And the final piece, the template itself, can look like this:

File: ansible-managed-nagios-hosts.j2

{% for host_name, host in hostvars.iteritems() %}

define host {
        use                  linux-server
        host_name            {{ host['inventory_hostname_short'] }}
{% if host['group_names'] | select('match', '^nagios-hostgroup-.+') | list | count > 0 %}
        hostgroups           {{ host['group_names'] | select('match', '^nagios-hostgroup-*') | map('regex_search', '^nagios-hostgroup-(?P<id>.+)','\\g<id>') | sum(start = []) | join(",") }}
{% endif %}
        alias                {{ host_name }}
        address              {{ host['ansible_host'] }}
        }

{% endfor %}

Notice how we use a regex match in the jinja2 template to only create nagios hostgroups from ansible host groups on certain ansible host group prefixes.

This will result in nagios config that looks like this:

define host {
        use                  linux-server
        host_name            dev3
        hostgroups           dev-servers,dev-dbs
        alias                dev3.lab
        address              192.168.1.111
        }

define host {
        use                  linux-server
        host_name            dev4
        hostgroups           dev-servers
        alias                dev4.lab
        address              192.168.1.112
        }