【问题标题】:Ansible: lineinfile module with regexp and looping to add line without regexpAnsible:带有正则表达式的lineinfile模块并循环添加没有正则表达式的行
【发布时间】:2022-01-22 01:24:45
【问题描述】:

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

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

寻找一些方法将这两项任务结合在一起..

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,并正在寻找一些建议

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    有一种方法可以使用omit 过滤器make variables optional。我们可以将它用于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
    

    【讨论】:

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