【问题标题】:How to escape the '#' comment character within Ansible lineinfile module?如何在 Ansible lineinfile 模块中转义“#”注释字符?
【发布时间】:2015-05-09 23:13:20
【问题描述】:

如何在 Ansible 的 lineinfile 模块中转义字符?

这是我要在服务器上插入的行:

EMAIL='hi@demo.com' # Server notification email address enter only 1 address

但是当我尝试以下操作时,由于 YAML 错误,Ansible 拒绝解析它:

line="EMAIL='{{ email_address }}' # Server notification email address enter only 1 address"

我猜是因为我有一个奇怪的双引号、单引号、等号和井号字符的组合。

【问题讨论】:

  • 不完全是一个干净的解决方案,但你可以让' 成为你变量本身的一部分吗?你也试过转义单引号和等号吗?
  • 如何转义单引号和等号?从理论上讲,ansible 不需要在双引号内转义单引号,但它当然值得一试。我实际上在想我需要转义“#”符号,但不知道该怎么做。我尝试了 '\#' 并且 Ansible 接受了它(这就是我认为这是根本问题的原因),但随后 Ansible 将整个 '\#' 放在服务器上,所以显然它并没有按预期工作。

标签: escaping yaml ansible


【解决方案1】:

问题确实是您的字符串中的# - 无论出于何种原因。

虽然您可以使用此技巧轻松防止解析错误:

line="EMAIL='{{ email_address }}' {{ '#' }} Server notification email address enter only 1 address"

【讨论】:

    【解决方案2】:

    对于较长的 cmets 或为了便于阅读,您还可以将 cmets 添加为 vars:

    name: Do something
    vars:
      comment: '# Server notification email address enter only 1 address'
    lineinfile:
      ...
      line="EMAIL='{{ email_address }}' {{ comment }}"
    

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多