Search code examples
jinja2salt-project

about escape in jinja2 template with saltstack


I have encountered an issue while using SaltStack. I noticed that when rendering a Jinja2 template, the variables are always being escaped.

example:

# pillar values
"args": "-DVMPORT=\"[{\"originport\":\"8080\",\"portname\":\"http\",\"ports\":[{\"HostIP\":\"10.56.95.131\",\"HostPort\":\"8080\"}]}]\""

# after render
args: -DVMPORT="[{"originport":"8080","portname":"http","ports":[{"HostIP":"10.56.95.131","HostPort":"8080"}]}]"

I want to preserve the original format of a variable and prevent it from being escaped during Jinja2 template rendering.

like this:

input: 
"args": "-DVMPORT=\"[{\"originport\":\"8080\",\"portname\":\"http\",\"ports\":[{\"HostIP\":\"10.56.95.131\",\"HostPort\":\"8080\"}]}]\""

after render: 
args: -DVMPORT=\"[{\"originport\":\"8080\",\"portname\":\"http\",\"ports\":[{\"HostIP\":\"10.56.95.131\",\"HostPort\":\"8080\"}]}]\"

Solution

  • Your examples show it not being escaped. If you want the strings to be escaped for a JSON context:

    {{ args | tojson }}
    

    Depending on where you're using it, there may be better options.