bcmcfc
bcmcfc

Reputation: 26745

Ansible replace single quotes regexp

I have the following attempt in 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

To implement this regex:

regex101

in order to change:

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

to:

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

I've tried:

None of these, nor anything else I've found so far, has worked.

What is the correct way of implementing this in the confines of YAML?

Upvotes: 3

Views: 2559

Answers (2)

Abhishek Bhatnagar
Abhishek Bhatnagar

Reputation: 21

You need to change the lines to below -

regexp: "\'null\'"
replace: "null"

Also, you need to specify the hosts you would be going to run the playbook on. The complete playbook should look something like this -

- hosts: <hostname/groupname/all>
  
  tasks:

        - 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

Please double check the code indentation as well :)

Upvotes: 0

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39089

You have to double the backslashes, not the quotes.

In YAML, text scalars can be surrounded by quotes enabling escape sequences such as \n to represent a new line, \t to represent a tab, and \\ to represent the backslash.

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

The task:

- 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

would give:

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

Upvotes: 3

Related Questions