【问题标题】:Regular expression not finding any matches to replace text using ansible.builtin.replace正则表达式未找到任何匹配项以使用 ansible.builtin.replace 替换文本
【发布时间】:2022-01-05 18:33:26
【问题描述】:

我从一个剧本中获得了这个 Ansible 任务,我试图用它来用 /etc/ansible/hosts 中设置为变量的新主机名替换 /etc/hosts 中出现的主机名:

  - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: '^\w+-\w+'
      replace: "{{ new_hostname }}"

我试图更改 /etc/hosts 内容的 Ansible 目标的主机名是 webna-host0011,这也是我试图在 /etc/hosts 中捕获的模式和替换所有出现的。

当我运行 playbook 时,此任务没有找到任何匹配项来进行替换,并且 /etc/hosts 文件保持不变。

我使用 https://pythex.org/webna-host0011 作为我的测试字符串检查了正则表达式,并且能够获得正确的匹配,但是在任务本身中使用此表达式时找不到匹配项。

这是 /etc/hosts 本身:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

10.12.52.19     webna-host0011.onegrp.com webna-host0011

正则表达式匹配主机名本身,但似乎无法进行匹配,因为它位于文件本身的行中。

【问题讨论】:

  • 我觉得应该是regexp: '^\\w+-\\w+',但可能还不够。
  • 没有规则来定义你搜索的内容,你必须指明要替换的全名

标签: regex ansible


【解决方案1】:

在您的情况下,即没有规则来定义要替换的主机名:

 - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: 'webna-host0011'
      replace: "{{ new_hostname }}"

或替换所有包含 - 的字符串(小心):

 - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: \w+-\w+'
      replace: "{{ new_hostname }}"

【讨论】:

  • 我不明白为什么它不起作用,请查看链接测试,或者您的 etc/host 中有一些特殊的东西可以显示它吗?...
  • 您的行以 ip 开头,而不是主机名?
  • 感谢您的建议 (?m)。我从目标中添加了 /etc/hosts 的内容。由于主机名在文件行中的位置,似乎没有发生匹配。
  • 是的,但要小心,因为所有带有 - 的字符串都将被替换
  • 您确实不能让^ 开始您的正则表达式,因为^ 表示在行首,而在主机行的开头,您确实有,至少有一个 IPv4
猜你喜欢
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多