Ansible:如何正则表达式替换具有特殊字符的字符串?

问题描述 投票:0回答:2

我需要将配置文件中的一个字符串(具有特殊字符,如

{
(
]
等)替换为另一个字符串。

尝试使用下面的替换模块执行时出现一些语法错误:

- name: update password in config file
  become: true
  become_user: "{{ my_user }}"
  replace:
    path: /var/tmp/config.xml
    regexp: "{{ old_pwd.stdout }}"
    replace: "{{ new_pwd.stdout }}"
    backup: true

仅当正则表达式值包含特殊字符时,上述剧本才会失败,例如

gT5{t4(dfR]p

错误信息

An exception occurred during task execution. To see the full stack trace use -vvv. The error was: re.error: missing ), unterminated subpattern at position 5

具体

re.error: missing ), unterminated subpattern at position 5

输入有特殊字符时如何解决这个问题?

regex replace ansible
2个回答
0
投票

您可以使用

regex_escape
过滤器转义正则表达式模式以及替换模式中的特殊字符:

  replace:
    path: /var/tmp/config.xml
    regexp: "{{ old_pwd.stdout | regex_escape() }}"
    replace: "{{ new_pwd.stdout | regex_escape() }}"
    backup: true

0
投票

先具体回答一下,只有正则表达式字符串需要转义,建议使用单引号,参见如何用

ansible-playbook
替换含有多个特殊字符的行。

例如

config.xml
包含内容的文件

<password>p[gR\d)4t}5T</password>

一个最小示例剧本

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

  vars:

    old_pwd:
      stdout: p[gR\d)4t}5T

    new_pwd:
      stdout: gT5{t4(d\R]p

  tasks:

  - name: Update password in config file
    replace:
      path: config.xml
      regexp: '{{ old_pwd.stdout | regex_escape() }}'
      replace: '{{ new_pwd.stdout }}'

将产生预期的输出,即更改后的密码

<password>gT5{t4(d\R]p</password>

为了以更一般的方式回答,根据

config.xml
文件的内容和结构(不幸的是这里没有进一步指定),建议使用
xml
模块 – 管理 XML 文件的片段或字符串
代替。

 - name: Reset the password to 'default'
   community.general.xml:
     path: config.xml
     xpath: /password
     value: default

生成输出文件

config.xml
,内容为

<?xml version='1.0' encoding='UTF-8'?>
<password>default</password>

通过使用这种方法,根本不需要正则表达式和转义12

© www.soinside.com 2019 - 2024. All rights reserved.