Available template includes context

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?

+4
source share
1 answer

If you are using Jinja 2.0, this is to be expected. As mentioned in the documentation :

Note:

In Jinja 2.0, the context that was passed to the included template did not include the variables defined in the template. This didn't actually work:

 {% for box in boxes %} {% include "render_box.html" %} {% endfor %} 

The included render_box.html template render_box.html not available for access in Jinja> 2.0. Starting with Jinja 2.1, render_box.html can do this.

0
source

All Articles