I play with impossibility for almost two weeks, but I did not understand how the inclusion of the template in contexts works.
Jinja documentation says:
By default, the included context is passed the current context [...]
From this statement, I tried the following:
in the roles that I use on my servers, I export a fact that describes which check should be performed on each host (I'm trying to make a smart nagios_server role).
- name: tell nagios what to monitor set_fact: nagios_monitor="{{ nagios_monitor }} dns"
in the role of nagios, I create a basic template that will initiate all checks in one file. The checks themselves are defined in the included templates.
Cast / nagios _server / tasks / main.yml:
- name: configure Nagios checks template: src="{{ item }}.cfg.j2" dest="/etc/nagios3/conf.d/{{ item }}.cfg" with_items: - hosts - commands - checks - defaults notify: - restart nagios
Cast / nagios _server / templates / checks.cfg.j2:
{% for host in groups['all'] %} {% set checks = hostvars[host]['nagios_monitor'].strip().split(" ") %} # Checks for {{ host }} {% for elmt in checks %} {% if elmt != "" %} {% include "checks/"+elmt+".cfg.j2" with context %} {% endif %} {% endfor %} {% endfor %}
cast / nagios _server / templates / checks / dns.cfg.j2:
define service { host_name {{ host }} service_description DNS lookup check_command check_dns_lookup use generic-service }
And when I run the playbook, I get the following error:
fatal: [vagrant] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'host' is undefined", 'failed': True}
Am I missing something? How should I make it work?
source share