Ansible:将字符串附加到文件中的现有行

Pra*_*bre 10 ansible

我正在使用 ansible 模块来编辑 kube-apiserver 的清单文件

    - --feature-gates=AdvancedAuditing=true
Run Code Online (Sandbox Code Playgroud)

我想添加新的功能门,例如

    - --feature-gates=AdvancedAuditing=true,TTLAfterFinished=true
Run Code Online (Sandbox Code Playgroud)

我尝试了很多事情,其中​​之一 -

- name: append TTLAfterFinished to existing list of feature-gates
  lineinfile:
    path: item.0.item.file_path
    backrefs: yes
    regexp: "^(.*feature-gates.*)$"
    line: '\1,TTLAfterFinished=true'
Run Code Online (Sandbox Code Playgroud)

运气不好..:(有什么帮助吗?

Jac*_*ack 7

你对我来说效果很好,但我没有变量item。所以我有这个:

- name: append TTLAfterFinished to existing list of feature-gates
  lineinfile:
    path: "{{ role_path }}/files/file_path"
    backrefs: yes
    regexp: "^(.*feature-gates.*)$"
    line: '\1,TTLAfterFinished=true'
Run Code Online (Sandbox Code Playgroud)

也许item问题出在你的变量上。

  • 该解决方案不是幂等的,每次运行它时,都会将另一个副本添加到该行中。使用 `regexp: "^(match this.*?)( my extra data)?$` 这会进行非贪婪匹配 `.*?`,然后检查您的字符串是否已经位于末尾,然后替换该行仅在第一次匹配后使用额外数据。因此,这里的正则表达式应该是 `regexp: "^(.*feature-gates.*?)(,TTLAfterFinished=true)?$` (4认同)