Ansible 正则表达式转义美元字符 [英] Ansible regex escape dollar character

查看:39
本文介绍了Ansible 正则表达式转义美元字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Ansible 修改配置文件中的 URL 值

I'm trying to modify URL value in config file using Ansible

$CONSOLE_URI = "http://172.18.18.103/controller/";

我正在使用 lineinfile 模块,但它不起作用,我试图用双反斜杠转义 $,但它也没有用.

I'm using lineinfile module, but it doesn't work, I have tried to escape $ with double back slashes, but it hasn't worked either.

 - lineinfile: dest=/etc/log.conf regexp='^\\$CONSOLE_URI' line='$CONSOLE_URI=http://google.com';

推荐答案

我认为您的正则表达式是正确的.我刚刚对此进行了测试,写入文件的行实际上包含引号.这是/etc/log.conf的内容:

I think your regex is correct. I just tested this and the line written to the file actually has the quotes inside. This is the content of /etc/log.conf:

'$CONSOLE_URI=http://google.com';

如果这是您的意图,我不相信,您当然需要在正则表达式中添加引号.

If that was your intention, which I do not believe, you of course need to add the quotes to the regex.

不要问我为什么单引号有时有效有时无效.在这种情况下,您需要对行使用双引号,而对于正则表达式,单引号工作...

Don't ask me why the single quotes do sometimes work and sometimes not. In this case you need to use double quotes for line while for regexp the single quotes work...

- lineinfile: dest=/etc/log.conf regexp='^\\$CONSOLE_URI' line="$CONSOLE_URI=http://google.com"

无论如何,我强烈建议使用 YAML 语法而不是 key=value 语法.我发现后者非常难以阅读,而 Ansible 就是关于可读性的.在正确的 YAML 语法中,您还可以几乎完全删除引号,如果您使用包括单引号和双引号在内的更复杂的命令,这会很有帮助,然后您将不得不再次转义.所以理想情况下(我认为)你的任务应该是这样的:

Anyway, I highly suggest to use YAML syntax instead of key=value syntax. I find the latter extremely hard to read and Ansible is all about readability. In proper YAML syntax you also can trash quotes almost completely, which helps a lot if you use more complex commands which include both single and double quotes, which you then would have to escape again. So ideally (by my opinion) your task would look like this:

- lineinfile:
    dest: /etc/log.conf
    regexp: ^\$CONSOLE_URI
    line: $CONSOLE_URI=http://google.com

在这种情况下,您只需要对 $ 进行一次转义.

In that case you only need to escape the $ once.

这是用 Ansible 2.0.0.2 测试的.

This is tested with Ansible 2.0.0.2.

PS:不确定您的行的 ; 是否应该在文件中.

PS: Not sure about the ; of your line, if that was supposed to be inside the file or not.

这篇关于Ansible 正则表达式转义美元字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆