我尝试了 bash 转义和双引号方法来转义下面的 shell 命令中的特殊字符,但是两者都不起作用,在 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
这里的问题之一是冒号后跟一个空格:
。这通常是映射键的指示符。
YAML 不允许在一行上嵌套映射,例如:
foo: bar: baz
这就是 YAML 设计者选择禁止的原因:
在映射值中(如果它与键位于同一行)。 (也可以通过简单地忽略进一步发生的情况并将其视为常规内容来解决。)
你有多种选择。您可以将整个值放在引号中,在这种情况下这不是一个好主意,因为您同时有单引号和双引号,那么您必须转义它们。
解决方法是转义 sed 命令中的空格:
shell: date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date:\ //g') +0530"
更通用的解决方案是使用折叠块标量:
shell: >
date -s "$(curl -s --head http://google.com | grep '^Date:' | sed 's/Date: //g') +0530"
您现在甚至可以将其分成几行,因为折叠块标量会将连续的行折叠为一行:
shell: >
date -s "$(curl -s --head http://google.com
| grep '^Date:' | sed 's/Date: //g') +0530"
正如哈维尔提到的,第二个问题是 sed 表达式s/Date/: //g
。你可能想要s/Date: //g
。另请参阅 @tripleee 如何改进命令的建议。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)