如何在 Ansible(脚本模块)中转义反斜杠和双引号 [英] How to escape backslash and double quote in Ansible (script module)
问题描述
我对 Ansible (2.x) 非常陌生,我在使用脚本模块和使用双引号和反斜杠传递参数时遇到问题.
I'm very new to Ansible (2.x) and I am having trouble using the script module and passing parameters with double quotes and backslashes.
假设我们有一个包含字符串foo"的集合变量 {{foo}}
,我有一个这样的任务:
Assuming we have a set variable {{foo}}
which contains a string "foo", I have a task like this:
set_fact:
arg: \(-name "{{foo}}" \)
name: call shell module
script: path/somescript.sh "{{arg}}"
我的脚本需要以下参数结构才能工作:
My script needs the following structure of the argument in order to work:
\(-name "foo" \)
我尝试了几种方法,例如:
I tried several things such as:
arg: \(-name \""{{foo}}"\" \) result: \\(-name \"foo\" \\)
arg: '\(-name \""{{foo}}"\" \)' result: \\(-name \"foo\" \\)
arg: \\(-name \""{{foo}}"\" \\) result: \\(-name \"foo\" \\)
是否可以在 Ansible 中转义反斜杠和双引号?
Is it possible to escape backslashes and double quotes in Ansible?
推荐答案
不要被 ansible-playbook 以 JSON 编码的形式打印调试消息的事实所迷惑,所以一些字符被转义了.
Don't be confused by the fact that ansible-playbook prints debug messages in JSON encoded form, so some characters are escaped.
set_fact:
arg: \(-name "{{foo}}" \)
您的语法正确.如果 foo
的值为 bar
,这会将 arg
设置为 \(-name "bar"\)
.
但这种情况下的调试消息将如下所示:
You have correct syntax. This will set arg
to \(-name "bar" \)
if foo
's value is bar
.
But the debug message in this case will look like this:
ok: [localhost] => {
"arg": "\\(-name \"bar\" \\)"
}
请注意,JSON 的特殊字符("
和 \
)已转义.
Note that special characters for JSON ("
and \
) are escaped.
但是将其作为参数传递可能存在一些问题.
如果你这样调用你的脚本
But there may be some issues with passing this as parameter.
If you call your script like this
script: path/somescript.sh "{{arg}}"
参数字符串看起来像这样 "\(-name "bar" \)"
它实际上是 bash 中的 3 个串联字符串:\(-name
+bar
+ \)
,因此您将在 bar 周围丢失双引号.
Parameter string will look like this "\(-name "bar" \)"
which is actually 3 concatenated strings in bash: \(-name
+bar
+ \)
, so you will lose double quotes around the bar.
如果您想保留那些双引号,请使用:
If you want to preserve those double quotes, use:
script: path/somescript.sh '{{arg}}'
这篇关于如何在 Ansible(脚本模块)中转义反斜杠和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!