Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to include another Jinja2 template in an Ansible context in Jinja2

I have an Ansible playbook that sets a lot of variables. One the playbooks has this task:

- name: create config file 
  template:
    src: 'templates/main_config.j2'
    dest: "{{ tmp_dir }}/main_config.json"

The template main_config.j2 writes strings that are defined as variables in the parent Ansible playbooks and tasks.

I want to include another Jinja2 template based on a value of an Ansible variable.

{% include "./templates/configurations.j2" %}, 
{% include "./templates/security.j2" %},
{% include './templates/' + {{ job }} + '_steps.j2' %}

job is a Ansible variable set in a parent playbook.

This is not working. What could be the problem?

like image 820
saurabh daga Avatar asked Mar 13 '17 09:03

saurabh daga


People also ask

Does Ansible use Jinja2 template?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.

How do I import Jinja2?

Select your current project. Click the Python Interpreter tab within your project tab. Click the small + symbol to add a new library to the project. Now type in the library to be installed, in your example "jinja2" without quotes, and click Install Package .


1 Answers

You don't need to open a Jinja2 expression ({{ ... }}) to refer to a variable inside a statement ({% ... %}). You can use the variable name directly:

{% include './templates/' + job + '_steps.j2' %}
like image 91
techraf Avatar answered Sep 21 '22 05:09

techraf