首页 > 解决方案 > Ansible 替换单引号正则表达式

问题描述

我在ansible中有以下尝试:

---
- name: Replace string nulls with php nulls in config
  ansible.builtin.replace:
    path: "{{ app_root_path }}/config/autoload.local.php"
    regexp: "\'''null\'''"
    replace: 'null'
    backup: yes

要实现这个正则表达式:

正则表达式101

为了改变:

'host'     => 'null',
'user'     => 'null',
'password' => 'null',

至:

'host'     => null,
'user'     => null,
'password' => null,

我试过了:

这些都没有,到目前为止我发现的任何其他东西都没有奏效。

在 YAML 范围内实现这一点的正确方法是什么?

标签: ansible

解决方案


您必须将反斜杠加倍,而不是引号。

在 YAML 中,文本标量可以用引号括起来,从而启用转义序列,例如\n表示新行、\t表示制表符和\\表示反斜杠。

来源:https ://yaml.org/spec/history/2001-08-01.html#sec-concept

任务:

- name: Replace string nulls with php nulls in config
  ansible.builtin.replace:
    path: "{{ app_root_path }}/config/autoload.local.php"
    regexp: "\\'null\\'"
    replace: 'null'
    backup: yes

会给:

'host'     => null,
'user'     => null,
'password' => null,

推荐阅读