Unable to get double-backslashes right on windows

In my role I have one step which sets up some pathing:

  • name: Set consul folder var
    set_fact:
    consul_folder: “{{ ansible_env[‘DatafilesPath’] }}\apps\consul”

This works in Ansible and I can use the ‘consul_folder’ variable in other plays and all is good.
I also need to set this path in a config file which gets templated onto the target server. The relevant parts of the json looks like this:

{
“datacenter”: “{{ consul_dc_name }}”,
“data_dir”: “{{ consul_folder }}\data”,

As far as I’m in ansible the data_dir is a valid path, as all backslashes get normalized into their “real” value. However, on the target node this file ends up like this:

{
“datacenter”: “default”,
“data_dir”: “C:\apps\consul\data”,

From this I gather that Ansible does not normalize json data.

The problem I have is that I need the target json to contain the “double backslash” so that it’s a valid json file.
The alternative I see right now is to double-double the backslashes but that will get incredibly messy incredibly fast.

I have tried using a jinja2 filter in my template json:

{
“datacenter”: “{{ consul_dc_name }}”,
“data_dir”: “{{ consul_folder | win_dirname}}\data”,

but the result is the same.

Is there a way for me to get around this so that the double quotes are retained and thus the template json kept valid?

For the record, I also tried the builtin jinja replace filter:

{
“datacenter”: “{{ consul_dc_name }}”,
“data_dir”: “{{ consul_folder |replace(‘',’\') }}\data”,

But that just caused Ansible to choke.

I believe the filter to_json should work

"data_dir": "{{ consul_folder | to_json }}\\data",

good idea! I’ll try!