Search code examples
powershellansibleyamlwin-shell

PowerShell {% if %} {% endif %} syntax throws an error


I wrote this PowerShell script:

- name: Some name
  win_shell: |
    [xml]$myFile = Get-Content "C:\MyFile.xml"
    $myFile.SelectSingleNode("//some-element").InnerText = "new text"
    {% if 1 -eq 1 %}
    $myFile.SelectSingleNode("//another-element").InnerText = "new text"
    {% endif %}
    $myFile.Save("C:\MyFile.xml")

and I am getting this error:

"template error while templating string: expected token 'end of statement block'"

Am I doing something wrong? Can someone please help?


Solution

  • The reason for the error is Jinja2 Templating. The compare statement need to be in Jinja2 syntax, {% if 1 == 1 %} instead of Shell syntax. This is because the templating will be done on the Control Node in Python and before sending over the Shell commands to the Windows Remote Node.

    Similar Q&A

    Documentation