有时候在使用 Ansible 的 lineinfile 模块时,指定 insertafter 参数插入一行文本并不总是生效,无法插入到正确的行之后。这很有可能是因为匹配的行不是想要的。可以使用正则表达式来确保匹配到正确的行。
以下是一个示例 playbook 的代码,它在文件 /etc/hosts 中插入一行文本 “192.168.1.100 webserver”:
- name: add webserver to hosts file
hosts: web
become: yes
tasks:
- name: insert a line after matching the pattern
lineinfile:
path: /etc/hosts
line: '192.168.1.100 webserver'
insertafter: '^127\.0\.0\.1 localhost$'
state: present
在上述代码中,insertafter 参数指定了一个正则表达式,它匹配到了 hosts 文件中的 “127.0.0.1 localhost” 行,并在该行之后插入了一行文本。
总之,正确使用正则表达式可以确保 lineinfile 模块的 insertafter 参数能够按预期工作。