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"
]
}