Kristi Jorgji
Kristi Jorgji

Reputation: 1731

Ansible jinja2 stop removing escaped double quote

defaults/main.yml

my_var: "[\"test\"]"

Then I render this in one template like template.j2

MY_VARS="{{ my_var }}"
- name: "create .env from template"
  template:
    src: "templates/template.j2"
    dest: ".env"

Result of rendering is:

MY_VARS="["d"]"

Is there a way to stop replacing \" with " by ansible?

Expected result of template rendering is:

MY_VARS="[\"d\"]"

Upvotes: 0

Views: 242

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Use single-quotated style. Quoting:

| ... the “\” and “"” characters may be freely used.

my_var: '[\"test\"]'

This is the only change needed. Your code works fine

shell> cat .env
MY_VARS="[\"test\"]"

Upvotes: 1

P....
P....

Reputation: 18371

Change :

my_var: "[\"test\"]"

to:

my_var: "[\\\"test\\\"]"

OR:

You can use the following as the template:(this is not tested)

MY_VARS="{{ my_var|tojson|regex_replace('^\\\"|\\\"$','') }}"

Upvotes: 1

Related Questions