ansible lineinfile 模块用多行替换单行

ansible lineinfile module to replace a single line with multiple lines

我有一个 ansible play 可以正常工作,如下所示,这里我有两个 From 条目正在用 TO 条目更改。

但我只是想知道在我的例子中是否有方法可以将名为 ntp.conf 的文件中的一行替换为两行。

---
- name: Play to correct the config for NTP clients
  hosts: all
  remote_user: root
  gather_facts: False

  tasks:
  - name: Changing the ntp server configuration on the client
    lineinfile:
      path: /etc/ntp.conf
      ### line to be searched & matched
      regexp: '{{ item.From }}'
      ### line to be in placed
      line: '{{ item.To }}'
      state: present
      backup: yes
      backrefs: yes

    with_items:
    - { From: 'server ros-ntp minpoll 4 maxpoll 10', To: 'server ros-gw.fuzzy.com minpoll 4 maxpoll 10'}
    - { From: 'server ros-ntp-b minpoll 4 maxpoll 10', To: 'server ros-b-gw.fuzzy.com minpoll 4 maxpoll 10'}

    notify: restart_ntp_service

  handlers:
  - name: restart_ntp_service
    service:
      name: ntpd
      state: restarted

您需要使用 blockinfilentp.conf 添加多行。您可以使用 lineinfile 将您的目标行替换为评论,然后使用 blockinfileinsertafter 参数在其后添加您的行。

这里是blockinfiledocumentation.

或者,您可以使用两个 lineinfile 任务并利用 insertafter 属性。像这样:

- name: Set NTP server to use ros-ntp-b
  lineinfile:
      path: /etc/ntp.conf
      regexp: 'server ros-ntp-?b? minpoll 4 maxpoll 10'
      line: 'server ros-ntp-b minpoll 4 maxpoll 10'
      state: present
      backup: no

- name: Add NTP server config for ros-ntp-gw
  lineinfile:
      path: /etc/ntp.conf
      regexp: 'server ros-ntp-rw minpoll 4 maxpoll 10'
      line: 'server ros-ntp-gw minpoll 4 maxpoll 10'
      insertafter: 'server ros-ntp-b minpoll 4 maxpoll 10'
      state: present
      backup: yes

我使用 lineinfile 模块解决了以下问题,如果有人遇到,我仍在寻找其他方法。只是将工作答案放在下面以供后代使用...

---
- name: Play to correct the config for NTP clients
  hosts: all
  remote_user: root
  gather_facts: False
  tasks:
  - name: Changing the ntp server configuration on the client
    lineinfile:
      path: /etc/ntp.conf
      ### line to be searched & matched
      regexp: 'server ros-ntp minpoll 4 maxpoll 10'
      ### line to be in placed
      line: "server ros-ntp-b minpoll 4 maxpoll 10\nserver ros-ntp-gw minpoll 4 maxpoll 10"
      state: present
      backup: yes
      backrefs: yes
    notify: restart_ntp_service

  handlers:
  - name: restart_ntp_service
    service:
      name: ntpd
      state: restarted

换行符 \n 适用于版本 2.3 和 2.4 qs,只是要确保不要使用实际 git 提交中的 \n <- thi sis。

    # Replace the newline character with an actual newline. Don't replace
    # escaped \n, hence sub and not str.replace.
    line = re.sub(r'\n', os.linesep, params['line'])
    # Replace the newline character with an actual newline, but be careful
    # not to trigger other escape sequences (specifically octal \ooo)
    line = re.sub(r'((?<!(?:[^\]\))\n)', os.linesep, params['line'])