将Ansible中字符串中的特殊字符替换为Ansible的给定字符串中的特定字符



在我的ansible剧本中,我需要从用户那里获得一个字符串输入,该字符串可能具有特殊字符,如双引号(")、反命题。我想在每一个这样特殊的字符前面加上\(斜线)。

例如,

"(msg.commandCode=303或msg.Command Code=302或msg.CcommandCode=301)和msg.dest-host avpExists";

将更改为

\"(msg.commandCode=303或msg.Command Code=302或msg.CcommandCode=301\)和msg.dest-host avpExists\">

有人能帮我吗?

|regex_replace滤波器是为此目的而设计的

- debug:
msg: the new string is {{ the_string | regex_replace(re1, re2) }}
vars:
the_string: '"(msg.commandCode=303 or msg.commandCode=302 or msg.commandCode=301) and msg.dest-host avpExists"'
re1: '(["()])'
re2: '\1'

其中\是字面反斜杠字符,1是对第一个捕获组(只有一个)的引用

我发现使用vars:和单引号字符串比使用yaml和反斜杠更容易,但如果你能找到正确数量的额外反斜杠来使用,它会很好地内联到jinja2管道中

最新更新