You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible replace模块修改pi-hole.toml配置的问题及解决方案

问题:Ansible replace模块无法修改pihole.toml中的domain配置

我尝试更新pihole.toml文件的配置项,先后用了lineinfile和replace模块,但都没能成功修改目标内容。

第一次尝试(模糊匹配)

使用replace模块尝试匹配并替换domain配置,代码如下:

- name: Configure pihole.toml settings.
  ansible.builtin.replace:
    path: /etc/pihole/pihole.toml
    regexp: "{{ item.regexp }}"
    replace: "{{ item.replace }}"
    after: "{{ item.after }}"
    before: "{{ item.before }}"
  loop:
    - { 
        regexp: '^  domain =.*$',
        replace: '  domain = "{{ pi_hole_domain }}" ### CHANGED, default = "pi.hole"',
        after: '^\[webserver\]$',
        before: '^  \[webserver.session\]'
      }

文件中默认值为 domain = "pi.hole"(前置空格为有意设置),但Ansible仅返回ok状态,未执行任何替换操作。

第二次尝试(精准匹配)

改为精准匹配默认值,结果依旧返回ok,无任何修改:

- name: Configure pihole.toml settings.
  ansible.builtin.replace:
    path: /etc/pihole/pihole.toml
    regexp: "{{ item.regexp }}"
    replace: "{{ item.replace }}"
    after: "{{ item.after }}"
    before: "{{ item.before }}"
  loop:
    - { 
        regexp: '^  domain = "pi\.hole".*$',
        replace: '  domain = "{{ pi_hole_domain }}" ### CHANGED, default = "pi.hole"',
        after: '^\[webserver\]$',
        before: '^  \[webserver.session\]'
      }

目标文件片段

pihole.toml中需要修改的相关内容片段:

# Some other sections and configurations here

[webserver]
  # On which domain is the web interface served?
  #
  # Possible values are:
  #     <valid domain>
  domain = "pi.hole"

  # Some other configurations here

  [webserver.session]
 
  # Some other configurations here

解决方案

问题根源在于多行模式未启用,给after参数添加多行模式标志(?m)后即可正常工作,最终可行配置如下:

- name: Configure pihole.toml settings.
  ansible.builtin.replace:
    path: /etc/pihole/pihole.toml
    regexp: "{{ item.regexp }}"
    replace: "{{ item.replace }}"
    after: "{{ item.after }}"
    before: "{{ item.before }}"
  loop:
    - { 
        regexp: '^  domain = "pi\.hole".*$',
        replace: '  domain = "{{ pi_hole_domain }}" ### CHANGED, default = "pi.hole"',
        after: '(?m)^\[webserver\]$',
        before: '  \[webserver.session\]'
      }

说明:regex参数默认支持多行模式,测试发现可以通过(?m)为after参数启用多行模式,但before参数似乎不支持该标志。

内容的提问来源于stack exchange,提问作者Eschin Tenebrous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:52:39