繁体   English   中英

ansible lineinfile模块,用多行替换单行

[英]ansible lineinfile module to replace a single line with multiple lines

我有一个很正常的游戏,其工作原理如下,这里有两个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

您需要使用blockinfile将多行添加到ntp.conf 您可以使用lineinfile将目标行替换为注释,然后使用insertafter参数在blockinfile添加行。

这是blockinfile 文档

或者,您可以使用两个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 commit中使用\\\\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']) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM