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:
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:
So then our Ansible task can look like this:
And the final piece, the template itself, can look like this:
File: ansible-managed-nagios-hosts.j2
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: