Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I escape a + character in ansible replace module

Tags:

ansible

I'm trying to add a trailing slash to a line in a config file, but the change is not made, even though there is no error returned. This is what I've tried so far

- replace:
    path: /etc/aide.conf
    regexp: "/var/log LOG+ANF+ARF"
    replace: "/var/log/ LOG+ANF+ARF"
    backup: yes

The problem, as I have noticed, lies in the + character.

I tried escaping them like this:

- replace:
    path: /etc/aide.conf
    regexp: "/var/log LOG\+ANF\+ARF"
    replace: "/var/log/ LOG\+ANF\+ARF"
    backup: yes

but then I get a "found unknown escape character" error.

I also tried this:

regexp: r"/var/log LOG\+ANF\+ARF"

What am I doing wrong?


1 Answers

Do not escape the replace string. It's not a regex. It's simply a string that shall replace the regex. The plus sign has no special meaning in replace, e.g.

    - replace:
        path: aide.conf
        regexp: "/var/log LOG\\+ANF\\+ARF"
        replace: "/var/log/ LOG+ANF+ARF"
        backup: yes

gives (see options --check --diff)

TASK [replace] *************************************************************
--- before: aide.conf
+++ after: aide.conf
@@ -1 +1 @@
-/var/log LOG+ANF+ARF
+/var/log/ LOG+ANF+ARF

See 7.3.1. Double-Quoted Style vs. 7.3.2. Single-Quoted Style. It's not necessary to escape the backslash in a single-quoted regex, e.g. the task below gives the same result

    - replace:
        path: aide.conf
        regexp: '/var/log LOG\+ANF\+ARF'
        replace: "/var/log/ LOG+ANF+ARF"
        backup: yes
like image 178
Vladimir Botka Avatar answered Jan 21 '26 14:01

Vladimir Botka