我有一个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
最佳答案
您需要使用blockinfile
向ntp.conf
添加多行。您可以使用lineinfile
将目标行替换为注释,然后使用insertafter
的blockinfile
参数在其后面添加行。
这是blockinfile
documentation。
或者,您可以使用两个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