如何在ansible shell模块中转义特殊字符 [英] How to escape special characters in ansible shell module

查看:201
本文介绍了如何在ansible shell模块中转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了 bash 转义和双引号方法来转义以下 shell 命令中的特殊字符,但两者都不起作用,在 ansible playbook 中转义特殊字符的正确方法是什么?

I tried bash escape and double quotes methods to escape the special characters in below shell command, But both didn't work, What is the proper way to escape special characters in ansible playbook?

 The offending line appears to be:

                 name: Syncing system date with htpdate failed!, Trying wget method...
                 shell: date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date: //g' ) +0530"
                                                                                                ^ here

    exception type: <class 'yaml.scanner.ScannerError'>
    exception: mapping values are not allowed in this context
      in "<unicode string>", line 15, column 93

推荐答案

这里的问题之一是冒号后跟一个空格 :.这通常是映射键的指示符.

One of the problems here is the colon followed by a space :. This is usually an indicator for a mapping key.

YAML 不允许在一行上嵌套映射,例如:

YAML does not allow nested mappings on one line, e.g.:

foo: bar: baz

这就是为什么 YAML 设计者选择在映射值中禁止 : 如果它与键位于同一行.(也可以通过简单地忽略进一步的事件并将其视为常规内容来解决.)

That's why YAML designers chose to forbid : in a mapping value if it's on the same line as the key. (It could have been been solved as well by simply ignoring further occurances and treat that as regular content.)

您有多种选择.您可以将整个值放在引号中,在这种情况下这不是一个好主意,因为您有单引号和双引号,然后您必须将其转义.

You have several choices. You can just put the whole value in quotes, which is not a good idea in this case since you have both single and double quotes which you would have to escape then.

一种解决方法是在 sed 命令中转义空格:

A workaround can be to escape the space in the sed command:

shell: date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date:\ //g') +0530"

更通用的解决方案是使用折叠块标量:

A more general solution is to use a folded block scalar:

shell: >
  date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date: //g') +0530"

你现在甚至可以把它分成几行,因为折叠块标量会将连续的行折叠成一行:

You could even seperate this into several lines now, because the folded block scalar will fold consecutive lines into one:

shell: >
  date -s "$(curl -s --head http://google.com
  | grep '^Date:' | sed 's/Date: //g') +0530"

第二个问题是,正如 Javier 提到的,sed 表达式 s/Date/://g.您可能需要 s/Date://g.另请参阅@tripleee 的建议如何改进您的命令.

The second problem is, as Javier mentioned, the sed expression s/Date/: //g. You probably want s/Date: //g. Also look at the suggestion by @tripleee how to improve your command.

这篇关于如何在ansible shell模块中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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