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

Updated:   |  Ansible articles

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.

---
- hosts: all
  tasks:
  - name: "Replace 'Hello' with 'Goodbye'"
    ansible.builtin.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. The debug module can be used to output the variable, like this.

---
- hosts: all
  vars:
    foo: "Hello World"
  tasks:
  - name: "output the contents of the 'foo' variable"
    ansible.builtin.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.

---
- hosts: all
  vars:
    foo: "Hello World"
  tasks:
  - name: "output the contents of the 'foo' variable, replacing 'Hello' with 'Goodbye'"
    ansible.builtin.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



Comments


Add a Comment


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