How to replace unknown strings?

Viewed 120

I am working on a playbook and I need to find out a way to replace some specific values (like in the bellow example) for values I will have in variables. The problem is, the values to be replace will be different every time I run the playbook.

define( 'DB_NAME', 'somestring' );
define( 'DB_USER', 'somevalue' );
define( 'DB_PASSWORD', 'someothervalue' );

I am considering the module ansible.builtin.replace or even the module shell but I still couldn't figure out a way to make it work. I am new to ansible and IT in general and kind of still don't understand how regular expressions work.

I was trying like this but as you can see, I have absolute no idea what I am doing:

- name: Replace between the expressions (requires Ansible >= 2.4)
  ansible.builtin.replace:
    path: /home/marcelo/public_html/wp-config.php
    after: "define( 'DB_NAME', '"
    before: "');"
    regexp: "*"
    replace: "{{ DBNM }}"

Some suggestions or examples I could use to start from would help a lot.

1 Answers

Using the replace-module is the way to go. You are already thinking in the right way with after and before, but those match the whole line, not part of it (you can by this specify a part in a file where the replace should be happening).
In your case, you need to pack all the logic into the regexp:

- name: Replace between the expressions (requires Ansible >= 2.4)
  ansible.builtin.replace:
    path: /home/marcelo/public_html/wp-config.php
    regexp: "define\\( 'DB_NAME', '.*' \\);"
    replace: "define( 'DB_NAME', '{{ DBNM }}' );"
Related