【问题标题】:Problem with regexp in ansible module shellansible模块外壳中的正则表达式问题
【发布时间】:2020-02-14 02:19:09
【问题描述】:

在我的 ansible-playbook 中,任务实现了用字符替换文件文本中的问题。我正在使用带有 sed 的 ansible 模块外壳。

我想解决问题

txt.file:Some text @@VAR_NUMBER_ONE@@

新的txt.file:Some text {{VAR_NUMBER_ONE}}

  - name: sed
      shell: sed -i 's|@@\([a-zA-Z_ ]*\)@@|\{{\1}}|g' txt.file

我遇到了致命错误

致命:[本地主机]:失败! => { "msg": "在模板化 's|@@\([a-zA-Z_ ]*\)@@|\{{\1}}|g' 时发生未处理的异常。错误是原始消息:意外char u'\\' at 25" }

【问题讨论】:

  • 试试sed -i 's|@@\([^@]*\)@@|{{\1}}|g' txt.file。不确定,但您可能需要将每个反斜杠加倍。

标签: python regex shell ansible


【解决方案1】:

问:“用字符替换文件中的文本”

txt.file 之前:Some text @@VAR_NUMBER_ONE@@

txt.file 之后:Some text {{VAR_NUMBER_ONE}}

A:下面的任务完成了这项工作。

- replace:
    path: "txt.file"
    regexp: '^(.*)@@(.*)@@$'
    replace: '{{ "\1" + "{{" + "\2" + "}}" }}'

regexp 字符串解释:

  • ^ 字符串开头
  • (.*) 存储在\1 中的任何序列
  • @@ 匹配 @@
  • (.*) 存储在\2 中的任何序列
  • @@ 匹配 @@
  • $ 字符串结尾

replace 字符串是由 4 个字符串串联创建的,因为在 YAML 中,{{}} 用于扩展变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多