Ansible - Replace data in a string or variable using the replace filter

The replace filter or regex_replace 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".  Notice in this example that Hello World is wrapped in quotes. When wrapped in quotes, Hello World is interpreted as a string.

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

 

Which should return the following.

TASK [Replace 'Hello' with 'Goodbye']
ok: [server1.example.com] => {
    "msg": [
        "Goodbye World"
    ]
}

 

Let's say you are using the vars plugin to create a variable, like this.

vars:
  foo: "Hello World"

 

The debug module can be used to output the variable, like this.

- name: "output the contents of the 'foo' variable"
  debug: 
    msg: "{{ foo }}"

 

Which should return the following.

TASK [output the contents of the 'foo' variable]
ok: [server1.example.com] => {
    "msg": [
        "Hello World"
    ]
}

 

The replace filter can be used to update the data in the foo variable, like this.

- name: "output the contents of the 'foo' variable, replacing 'Hello' with 'Goodbye'"
  debug: 
    msg: "{{ foo | replace('Hello', 'Goodbye') }}"

 

Which should return the following.

TASK [output the contents of the 'foo' variable, replacing 'Hello' with 'Goodbye']
ok: [server1.example.com] => {
    "msg": [
        "Goodbye World"
    ]
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

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 324a6 in the box below so that we can be sure you are a human.