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

查看:313
本文介绍了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.

不要问我为什么单引号有时有效而有时却无效.在这种情况下,您需要在行中使用双引号,而对于regexp,则使用单引号...

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天全站免登陆