如何在Ansible(脚本模块)中转义反斜杠和双引号 [英] How to escape backslash and double quote in Ansible (script module)

查看:1660
本文介绍了如何在Ansible(脚本模块)中转义反斜杠和双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆