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

Ansible win_shell执行PowerShell命令时双引号丢失问题求助

解决Ansible win_shell执行PowerShell时双引号丢失问题

问题背景

使用Ansible的win_shell模块执行PowerShell命令导入PFX证书时,命令中的双引号被自动省略,导致文件路径被错误识别,触发执行失败。手动在PowerShell中运行同一命令可正常执行,尝试过变量存储、/转义引号等方法均无效。

涉及的错误命令示例:

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\projectcorp.pfx", "$(ssl_cert_passcode}")

原Ansible任务脚本:

- name: Run command to import SSL certificate into VisualSVN Server
  win_shell: |
     New-Object  System.Security.Cryptography.X509Certificates.X509Certificate2("C:\projectcorp.pfx", "${ssl_cert_passcode}")
  args:
    executable: powershell.exe

解决方案

方案1:用PowerShell单引号包裹字符串,结合Ansible变量语法

PowerShell中,单引号包裹的内容会被当作字面量,不会被解析;同时直接使用Ansible的{{ 变量名 }}语法注入密码,避免多层解析冲突。

修改后的Ansible任务:

- name: Run command to import SSL certificate into VisualSVN Server
  win_shell: |
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2('C:\projectcorp.pfx', '{{ ssl_cert_passcode }}')
  args:
    executable: powershell.exe

方案2:在YAML中转义双引号

如果必须使用双引号,需要在YAML层面用\"转义双引号,确保PowerShell能接收到完整的引号包裹内容。

修改后的Ansible任务:

- name: Run command to import SSL certificate into VisualSVN Server
  win_shell: |
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(\"C:\projectcorp.pfx\", \"{{ ssl_cert_passcode }}\")
  args:
    executable: powershell.exe

方案3:用YAML单引号包裹整个PowerShell命令

将win_shell的命令内容用单引号包裹,让YAML不解析内部的双引号,直接传递给PowerShell执行。

修改后的Ansible任务:

- name: Run command to import SSL certificate into VisualSVN Server
  win_shell: >
    '$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\projectcorp.pfx", "{{ ssl_cert_passcode }}")'
  args:
    executable: powershell.exe

关键说明

  • 避免混用PowerShell变量语法(${变量名})和Ansible变量语法,优先用Ansible的{{ 变量名 }}在命令执行前完成变量注入。
  • YAML和PowerShell的引号解析规则不同,需要确保命令在两层解析后仍能保留正确的引号结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:28:39