【问题标题】:ansible lineinfile insert after every match每次匹配后插入ansible lineinfile
【发布时间】:2015-08-05 19:41:45
【问题描述】:

我想使用 ansible lineinfile 模块(或类似的模块)在特定正则表达式的 每个 匹配之后插入一行。 (lineinfile 只会在最后一个匹配之后插入)。

这看起来很简单。我发誓我先尝试了我的 google-fu。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    这是一个解决方案,它使用 Ansible 的 replace 模块和负前瞻正则表达式来确保幂等性。

    vars:
      find_this: "Row in the file"
      insert_this: "New line to be inserted"
      filename: "path/to/foo_file.txt"
    
    tasks:
      - name: multiline match and insert
        replace: >
          dest={{ filename }}
          regexp="^({{ find_this }}\n)(?!{{ insert_this }})"
          replace="\1{{ insert_this }}\n"
    

    【讨论】:

    • 很好,我正准备用这样的东西来解决我的问题,但你打败了我!
    • 很好,我只是在整理一个 perl 单行代码,认为lineinfile 可能无法进行负前瞻。perl -i -pe 'BEGIN{undef $/; $c="";} $c=s/(after_this)(?!\ninsert_this)/${1}\ninsert_this/smg; END{ print "CHANGED" if $c}' testfile。您可以将它与commandshell 模块一起使用,如果它替换了至少1 行,上面将打印“CHANGED”到标准输出,因此您需要执行register: resultchanged_when: "'CHANGED' in result.stdout" 之类的操作。这也有效,但您的解决方案更简单:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多