如何为Ansible Ad-hoc同时传递命名参数与自由格式参数?
如何在Ansible Ad-hoc模式下为win_command同时传递自由格式与命名参数
你完全可以在Ad-hoc模式下给win_command同时传递自由格式命令和命名参数,核心是要正确区分两者的写法——不需要加额外的破折号,直接把命名参数以key=value的形式跟在自由格式命令后面即可。
正确的命令格式
对于你提到的Playbook示例:
- name: Run an executable and send data to the stdin for the executable win_command: powershell.exe args: stdin: Write-Host test
对应的Ad-hoc命令应该是:
ansible <your_host> -m win_command -a 'powershell.exe stdin="Write-Host test"'
如果需要传递多个命名参数(比如你提到的arg1、arg2),只需要在后面继续追加key=value即可:
ansible <your_host> -m win_command -a 'powershell.exe stdin="C:\some\script.ps1" arg1=value_1 arg2=value_2'
为什么你的尝试失败了?
你之前的命令里加了多余的-:
# 错误写法 -m win_command -a 'powershell - stdin=C:\some\script.ps1 -arg1 value_1 -arg2 value_2'
这里的-会被Ansible识别为自由格式命令的一部分(也就是PowerShell的参数),导致PowerShell收到了无效的-参数而报错。win_command的命名参数不需要前缀破折号,直接用key=value形式即可。
注意事项
如果命名参数的值包含空格、特殊字符或者路径,记得用引号把值括起来,避免被shell解析错误。比如:
ansible <your_host> -m win_command -a 'powershell.exe stdin="Write-Host ''Hello World''"'
这里用双引号包裹PowerShell命令,内部的单引号用来处理字符串中的空格,适配bash等shell的引号规则;如果是在Windows的Cmd中执行Ad-hoc,可能需要调整引号的嵌套方式。
内容的提问来源于stack exchange,提问作者myxal
相关产品推荐
相关产品推荐

