Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Jinja2 substitution in Ansible playbook?

In my playbook, a JSON file is included using the include_vars module. The content of the JSON file is as given below:

{
  "Component1": {
    "parameter1" : "value1",
    "parameter2" : "value2"
  },

  "Component2": {
    "parameter1" : "{{ NET_SEG_VLAN }}",
    "parameter2": "value2"       
  }
}

After the JSON file is included in the playbook, I am using uri module to sent an http request as given below:

- name: Configure Component2 variables using REST API
  uri:
      url: "http://0.0.0.0:5000/vse/api/v1.0/config/working/Component2/configvars/"
      method: POST
      return_content: yes
      HEADER_x-auth-token: "{{ login_resp.json.token }}"
      HEADER_Content-Type: "application/json"
      body:  "{{ Component2 }}"
      body_format: json

As it can be seen, the body of the http request is send with the JSON data Component2. However, Jinja2 tries to substitute the {{ NET_SEG_VLAN }} in the JSON file and throws and undefined error. The intention is not to substitute anything inside the JSON file using Jinja2 and send the body as it is in http request.

How to prevent the Jinja2 substitution for the variables included from the JSON file?

like image 598
nitin_cherian Avatar asked May 31 '16 06:05

nitin_cherian


People also ask

Does Ansible use jinja2?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts. You can use templating with the template module.

How do you escape jinja2?

To escape jinja2 syntax in a jinja2 template with Python Flask, we can put render the template code without interpretation by putting the code in the {% raw %} block.

How do I know if jinja2 is installed?

To check which version of jinja2 is installed, use pip show jinja2 or pip3 show jinja2 in your CMD/Powershell (Windows), or terminal (macOS/Linux/Ubuntu) to obtain the output major.

What is Ansible unsafe text?

Unsafe or Raw StringsAnsible provides an internal data type for declaring variable values as “unsafe”. This means that the data held within the variables value should be treated as unsafe preventing unsafe character subsitition and information disclosure.


Video Answer


1 Answers

You should able to escape the variable even with {{'{{NET_SEG_VLAN}}'}} to tell jinja not to template anything inside that block.

like image 148
swaroop bhaskaruni Avatar answered Sep 22 '22 03:09

swaroop bhaskaruni