带有 "replace" 和 "after" 行进线的 Ansible 剧本不紧随其后

Ansible playbook with "replace" and "after" marching lines that are not directly after

用于更新 dhcpcd 的简单剧本代码

---
- name: Set ES heap min
  hosts: local

  tasks:
    - name: test task
      replace:
        path: /home/pedro/ansible_test/test.conf
        after: 'interface eth0'
        regexp: '^static ip_address=[0-9 ]*\.[0-9 ]*\.[0-9 ]*\.[0-9 ]*\/[0-9 ]*'
        replace: "static ip_address={{ ip_address }}/24"
        backup: yes

想法是更新特定接口的 IP(在本例中为 eth0) (注意我的正则表达式需要改进,但对正在发生的事情没有影响)

所以它作为日志正常工作,因为另一个接口被注释掉了,否则它将更新所有未被注释掉的接口中的行 static ip_address=

测试文件:

# Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
#static ip_address=192.168.1.30/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

如果像上面那样,那么除了 eth0 之外的配置文件将不会被触及,这是需要的。然而,如果 #static ip_address=192.168.1.30/2 行被注释,这一行也会被修改,这是不希望的。

查看 documentation 会发现具有“interface eth0”的行将被识别,并且只会修改具有匹配正则表达式的行,但这似乎不是真的。

运行 未注释行后的结果示例:


# Example static IP configuration:
interface eth0
static ip_address=192.168.1.390/24
static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.1.1
static domain_name_servers=192.168.1.1 #8.8.8.8 fd51:42f8:caae:d92e::1

# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
static ip_address=192.168.1.390/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

我是不是做错了什么,或者我是否误解了文档,或者这不是我描述的那样工作,是否存在错误?

请帮我理解

我是 运行 Ansible 1.9 和 python 3.8:

ansible --version
ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/pedro/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0]

我了解您的用例,您只想更新第一次出现 static ip_address= 的条目。正如评论中已经提到的,我发现 lineinfile 的方法适用于 dhcpcd.conf.

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:
    IP_ADDRESS: "192.0.2.0/24"

  tasks:

  - name: Update IP for eth0
    lineinfile:
      path: /etc/dhcpcd.conf
      regexp: '^static ip_address=[0-9 ]*\.[0-9 ]*\.[0-9 ]*\.[0-9 ]*\/[0-9 ]*'
      line: "static ip_address={{ IP_ADDRESS }}"
      firstmatch: true
      state: present
      backup: true