Ansible:带有正则表达式的 lineinfile 模块和循环添加没有正则表达式的行

Ansible: lineinfile module with regexp and looping to add line without regexp

我想使用 ansible lineinfile 模块在文件中添加一些行。

我正在尝试使用 regexp 匹配文件中的某些模式,我还有另一项任务是向 EOF 添加新行。目前,我正在执行 2 个任务,一个是添加新行,另一个是用于正则表达式循环...

正在寻找将这两项任务组合在一起的方法..

tasks:
    
- name: Add line to the file   
  lineinfile:
     path: "./file1"
     line: "testline"
     create: yes

- name: Add lines using regexp   
  lineinfile:
     path: "./file1"
     regexp: "{{ items.regexp }}"
     line: "{{ items.line }}"   
  loop:
     - { regexp: 'line1'
         line: 'value1'
       }
     - { regexp: 'line2'
         line: 'value2'
       }

我想在一个任务中完成这 2 个任务。我看到了一些选项,例如 EOF 和 insertafter,正在寻找一些建议

有一种方法可以 make variables optional 使用 omit 过滤器。我们可以将它用于 regexp 参数,这样如果它不存在于 loop 中,它就会被忽略。然后我们可以在循环中为同一个任务提供 line: testline

像这样:

    - name: Add lines to file
      lineinfile:
        path: "./file1"
        regexp: "{{ item.regexp | default(omit) }}"
        line: "{{ item.line }}"
        create: yes
      loop:
        - line: testline
        - regexp: line1
          line: value1
        - regexp: line2
          line: value2