Ivan Stoyanov
Ivan Stoyanov

Reputation: 5482

Ansible replace to replace a certain regex group

I am using the Ansible replace module to replace a string that is the first group of my regex expression.

- name: Replace my_address
      replace:
        dest=/etc/mydata/info.yaml
        regexp="^my_address\W\s(localhost)$"
        replace="{{ ansible_eth0.ipv4.address }}"

In my file I have several mentions of localhost and I want to replace localhost only on the following line: my_address: localhost.

So far the code abore replaces the whole line with the IP address. Is there a way to replace only the first group of the regex?

Upvotes: 1

Views: 6450

Answers (2)

U_R_Naveen UR_Naveen
U_R_Naveen UR_Naveen

Reputation: 788

To refer specific capturing group, you can use \g<1> or \g<groupName> in replacement. please refer https://docs.ansible.com/ansible/latest/collections/ansible/builtin/replace_module.html

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You need to use a lookbehind:

regexp="(?<=^my_address\W\s)localhost$"

See the regex demo

Only the consumed part (localhost) will get replaced then, and (?<=^my_address\W\s) will just check if there is my_address with a non-word character + whitespace before it.

Upvotes: 2

Related Questions