簡體   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