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

Ansible lineinfile正则匹配含空格行仅新增不替换问题求助

解决Ansible lineinfile只新增不替换的问题

问题出在你的正则表达式没有精准匹配到目标行,导致lineinfile判定无匹配项,从而执行新增操作而非替换。

修正后的Playbook代码

- name: update root password configuration line
  lineinfile:
    path: /etc/config
    regexp: '^password\s+root\s+.*$'
    line: 'password root {{ hello }}'

关键说明

  • 用\s+替代固定空格,匹配password与root、root与密码之间任意数量的空格,确保覆盖配置文件中可能存在的多空格场景
  • 如果目标行开头可能有缩进空格,可把正则调整为^\s*password\s+root\s+.*$,^\s*用于匹配行首的任意空格
  • lineinfile模块默认逻辑:当regexp匹配到现有行时直接替换该行;未匹配到时才会新增行,修正正则后即可实现预期的替换效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:15:08