用regexp替换在Ansible中不起作用(替换)

时间:2019-07-18 15:06:29

标签: ansible

我是Ansible的新手,我正在尝试写一部剧本来检查一行,如果没有注释掉,就去做。这是我要用//注释掉的行: $data['refresh_timeout'] = $data['Timeout'];

我已经在regex101.com中检查了搜索的语法,并且regexp似乎工作正常。看来我的问题出在replace上。 这是我的代码:

replace:
  path: /var/www/html/application/controllers/welcome.php
  regexp: r'^\s+(\$data\[\'refresh_timeout\'\].*)$'
  replace: r'^\s+// (\$data\[\'refresh_timeout\'\]\1'

我已经在2台服务器上进行了测试,在mytest-server2中该行已被注释掉,但是执行时ansible不会修改mytest-server1中的文件(无注释的行)。这就是我所拥有的:

`TASK [Gathering Facts]************************************************ 
task path: /home/myself/ansible/wui_refresh.yml:5
ok: [mytest-server2] 
ok: [mytest-server1]
META: ran handlers`

`TASK [Check whether /welcome.php contains "// $data['refresh_timeout']"] *****
task path: /home/myself/ansible/wui_refresh.yml:23
ok: [mytest-server1] => {"changed": false, "msg": ""}
ok: [mytest-server2] => {"changed": false, "msg": ""}
META: ran handlers
META: ran handlers`

`PLAY RECAP ***************************************************************
mytest-server2 : ok=2    changed=0    unreachable=0    failed=0
mytest-server1 : ok=2    changed=0    unreachable=0    failed=0`

在此先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

下面的任务完成了任务

- replace:
    path: /var/www/html/application/controllers/welcome.php
    regexp: '^\$data\[''refresh_timeout''\] = \$data\[''Timeout''\];'
    replace: '//$data[''refresh_timeout''] = $data[''Timeout''];'

之前

$ cat welcome.php
$data['refresh_timeout'] = $data['Timeout'];

之后

$ cat welcome.php
//$data['refresh_timeout'] = $data['Timeout'];

注释

  • Single-Quoted Style用于 regexp replace 。单引号必须转义('')。
  • regexp 使用Python正则表达式。特殊字符必须转义(\ $ ...)
  • 如果在行的开头有一个或多个空格,则 regexp 必须以'^ \ s +
  • 开头

答案 1 :(得分:0)

太棒了!它有效,我必须在正则表达式中添加\ s +。 非常感谢弗拉基米尔! 我投票赞成你,但我只有5分:(所以它没有显示...