大网数据广告活动
服务器运维问答

ansible replace regex with variable

· 52CE 我爱测

I am trying to replace localhost in the string $amp_conf['AMPDBHOST'] = 'localhost'; with the content of the variable {{ asterisk_db_host }} , which is 172.17.0.3 . Even though - replace: dest: /usr/src/freepbx/installlib/install…

问题原文

原帖链接 · Zulakis · CC BY-SA 3.0

I am trying to replace localhost in the string

$amp_conf['AMPDBHOST'] = 'localhost';

with the content of the variable {{ asterisk_db_host }}, which is 172.17.0.3.

Even though

- replace:
    dest: /usr/src/freepbx/installlib/installcommand.class.php
    regexp: '(\$amp_conf\[.AMPDBHOST.\] = .)localhost(.;)'
    replace: '\1\2'

perfectly results in

$amp_conf['AMPDBHOST'] = 'localhost';

- replace:
    dest: /usr/src/freepbx/installlib/installcommand.class.php
    regexp: '(\$amp_conf\[.AMPDBHOST.\] = .)localhost(.;)'
    replace: '\1{{ asterisk_db_host }}\2'

as well as

- replace:
    dest: /usr/src/freepbx/installlib/installcommand.class.php
    regexp: '(\$amp_conf\[.AMPDBHOST.\] = .)localhost(.;)'
    replace: '\1{{ asterisk_db_host|regex_escape() }}\2'

replace the string with O2.17.0.2'; or O2\.17\.0\.2';.

What am I doing wrong here? How can I properly do this replacement?

已采纳解答

原帖链接 · larsks · CC BY-SA 3.0

Your replacement string looks like this:

'\1{{ asterisk_db_host }}\2'

After Jinja templating, this is what actually gets used as the replacement string in the regex module:

'\1172.17.0.3\2'

Look at that first term. It's no longer \1, it's now \1172, which is clearly erroneous. One way of solving this is to make the quotes around the value part of your replacement (because when you do this, there will be a non-digit character -- the quote -- separating your backreference from the value of the template expansion). Here's one option:

- hosts: localhost
  gather_facts: false
  vars:
    asterisk_db_host: "172.17.0.3"
  tasks:
    - replace:
        dest: ./cfgfile
        regexp: >-
          (\$amp_conf\[.AMPDBHOST.\] = )'localhost'(;)
        replace: >-
          \1'{{ asterisk_db_host }}'\2

This uses YAML block quoting (>-) so that we don't need to worry about escaping quotes in our expressions, and it seems to do the right thing in my simple tests.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-01-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。