Search code examples
stringpowershellyamlquoting

How to quote this raw command in Ansible YAML?


I am using Ansible to manage the configurations of a bunch of Windows clients. For the record, Ansible playbooks (i.e. recipes) are written in YAML.

I need to run this command on every client, and I could test it successfully in a Powershell prompt on a client machine:

> CMD /C 'control intl.cpl,, /f:"C:\Temp\intlsettings.xml"'

(note the single quotes, required because of the double quotes around the filename)

Now I "just" need to write a YAML playbook and use the raw module from Ansible to send this command to a remote Powershell session. And this is where I am stuck. My command contains :, ' and " symbols so I have no idea how to quote it properly.

I have tried a million variations, with no success so far:

CMD /C 'control intl.cpl,, /f:"C:\Temp\intlsettings.xml"'
"CMD /C 'control intl.cpl,, /f:"C:\\Temp\\intlsettings.xml"'"
"CMD /C 'control intl.cpl,, /f:\"C:\\Temp\\intlsettings.xml\"'"
"CMD /C 'control intl.cpl,, /f\:\"C\:\\Temp\\intlsettings.xml\"'"

For information, the final playbook will look something like:

---
- name: Configure keyboard mappings
  hosts: windows

  tasks:
  - name: apply keyboard mappings config
    raw: CMD /C 'control intl.cpl,, /f:"C:\Temp\intlsettings.xml"'

Solution

  • If you execute this powershell command

    CMD /C 'control intl.cpl,, /f:"C:\Temp\intlsettings.xml"'
    

    powershell creates this CommandLine:

    "C:\Windows\system32\cmd.exe" /C "control intl.cpl,, /f:"C:\Temp\intlsettings.xml""
    

    Note, that no ' are used in the CommandLine.

    However, you don't need to go through cmd as no cmd functionality is used in your command.

    control.exe intl.cpl,, /f:"C:\Temp\intlsettings.xml"
    

    should be enough.

    I don't know ansible, but if I understand the documentation correctly, all text after raw is sent as a command via ssh. This means, it is interpreded by some shell. If this shell is cmd.exe, this should work:

    tasks:
      - name: apply keyboard mappings config
        raw: control.exe intl.cpl,, /f:"C:\Temp\intlsettings.xml"
    

    If the shell is powershell (v3 and above (default for win8 and above, installable for win7)), this should work:

    tasks:
      - name: apply keyboard mappings config
        raw: control.exe --% intl.cpl,, /f:"C:\Temp\intlsettings.xml"