Ansible - regex_replace

regex_replace or the replace filter can be used to replace data in a string or variable. The replace module is used to replace data in a file.

In this example, Hello is replaced with Goodbye.

- name: "replace 'Hello' with 'Goodbye'"
    msg: "{{ 'Hello World' | regex_replace('Hello', 'Goodbye') }}"


Which should return the following.

ok: [] => {
    "msg": "Goodbye World"


Let's say a variable named "foo" contains a value of Hello World.

  foo: "Hello World"


Notice in this example that foo is not wrapped in quotes. When wrapped in quotes, foo is interpreted as a string. When not wrapped in quotes, foo is be interpreted as a variable

- name: "replace 'Hello' with 'World'"
    msg: "{{ foo | regex_replace('Hello', 'Goodbye') }}"


Or, sometimes map may be preferred.

"{{ foo | map('regex_replace', 'Hello', 'World') | list }}"


Case Insensitive

(?i) can be included to perform a case insensitive match.

- name: "replace 'Hello' with 'World'"
    msg: "{{ foo | regex_replace('(?i)hello', 'Goodbye') }}"


Escaping literals

Let's say the foo variable contains a literal, a single period in this example.

  foo: "He.llo World"


Double back slashes are used to escape literals.

  msg: "{{ foo | regex_replace('He\\.llo', 'Goodbye') }}"


Or better yet, regex_escape can be used to escape literals.

- set_fact:
    foo: "{{ foo | regex_escape() }}"



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter b15a2 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |