BenMitchell1979
BenMitchell1979

Reputation: 81

Ansible 2.9 - Escape a single "\" backslash being passed into win_command from variable

 vars:
  - windowsLogonAccount: NT AUTHORITY\SYSTEM

 tasks:
 - name: Install Agent via CMD
    win_command: "config.cmd --windowsLogonAccount '{{ windowsLogonAccount }}'"
    args:
      chdir: "c:/agent"

I'm attempting to get just a single backslash to pass via Ansible to Windows. I've tried double backslashes "\\" and I've tried {{ var | safe }}, but without luck. I'm hoping somebody in the community can point me in the right direction. I can't believe it is as complicated as some of the other examples I've seen using replace and regex...

Everything I try I keep getting a double backslash:

2021-10-19T04:45:52.8643709Z TASK [Get Variable Output to Screen] *******************************************
2021-10-19T04:45:52.9042957Z     "msg": "My Variable Test Area 'NT AUTHORITY\\SYSTEM'"

Upvotes: 2

Views: 3396

Answers (2)

stackprotector
stackprotector

Reputation: 13560

I came here having not the exact same problem, but a similar one (passing an escaped backslash (\\) to the command), and my solution might also help here. When inserting variables into the command for command or win_command, it is always good to pipe the variable to the quote filter to preserve the content of the variable as is. In your case:

win_command: "config.cmd --windowsLogonAccount {{ windowsLogonAccount | quote }}"

Upvotes: 2

BenMitchell1979
BenMitchell1979

Reputation: 81

----Resolved----

So this is a unique thing with Ansible Outputs to Terminal. They write output in valid JSON and thus "auto" escape special characters like backslashes in the output. But the actual value passed during run-time does not contain both back slashes. I'm posting this in case any other Ansible noobs run into this surprise.

Example output to screen:

2021-10-19T04:46:11.6003956Z: [COMPUTERNAME]: CHANGED! => {"changed": true, "cmd": "config.cmd --unattended --windowsLogonAccount 'NT AUTHORITY\SYSTEM'

Actual output to host:

config.cmd --unattended --windowsLogonAccount 'NT AUTHORITY\SYSTEM'

Upvotes: 2

Related Questions