You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含Jinja2条件语句的PowerShell脚本执行报错,求助排查

Ansible win_shell模板错误:expected token 'end of statement block'

问题重现

你编写的Ansible任务代码:

- 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")

执行时触发错误:

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

错误原因

Ansible默认会对win_shell的参数内容进行Jinja2模板渲染。你在Jinja2的{% if %}条件块中使用了PowerShell的-eq比较运算符,但Jinja2语法体系里,相等判断用的是==而非-eq,这种语法不匹配导致模板解析器无法识别条件语句,进而抛出错误。

解决方案

有两种可行的修复方式:

方式1:改用Jinja2支持的条件语法

将{% if %}块中的-eq替换为Jinja2标准的==:

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

方式2:关闭Jinja2模板渲染

如果需要保留PowerShell风格的语法,或避免Jinja2解析这段内容,可通过以下两种方式实现:

方法A:使用raw参数(Ansible 2.10及以上版本支持)

- 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")
  args:
    raw: yes

方法B:使用!unsafe标记

- name: Some name
  win_shell: !unsafe |
    [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")

内容的提问来源于stack exchange,提问作者Keren_H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:08