Bootstrap FreeKB - Ansible - Escape literal characters using regex_escape
Ansible - Escape literal characters using regex_escape

Updated:   |  Ansible articles

There are two similiar but distinct filters that can be used to escape literal or special characters.

regex_escape can be used to escape literal characters in a string. In this example, fo.o contains the literal period character.

---
- hosts: localhost
  tasks:
  - name: encode special characters
    debug:
      msg: "{{ 'fo.o' | regex_escape }}"
...

 

Which should return the following. Notice the period is now escaped with two back slashes.

ok: [localhost] => {
    "msg": "fo\\.o"
}

 

Let's say a variable named "foo" contains a value of fo*o. Notice the wildcard character.

---
- hosts: localhost
  tasks:
  - name: encode special characters
    debug:
      msg: "{{ 'fo*o' | regex_escape }}"
...

 

Which should return the following. Notice the wildcard is escaped with two back slashes.

ok: [localhost] => {
    "msg": "fo\\*o"
}

 

Let's say you are doing a regular expression search that contains wildcards, like this.

when: "foo is not regex ('01 00 * * * /path/to/example.sh')"

 

Sometimes, you may just want to do something like this. In this example, the wildcard characters are wrapped in brackets.

when: "foo is not regex ('01 00 [*] [*] [*] /path/to/example.sh')"

 




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