使用Ansible中的replace模块替换带正则表达式的字符串

时间:2017-01-17 12:39:20

标签: regex replace ansible

我需要将app_name: <anything>的字符串替换为app_name: {{ node }}

尝试使用下面的替换模块执行时会出现一些语法错误:

  

replace:dest = / ABC / hybris / newrelic / newrelic.yml regexp =&#39; app_name:\ s [A-Za-z0-9] *&#39; replace =&#39; app_name:&#34; {{node}}&#34;&#39;

错误讯息:

[ansible@dev-ci ansible]$ ansible-playbook -i hosts_acc ACC.yml --tags=newrelic
ERROR! Syntax Error while loading YAML.


The error appears to have been in '/ABC/Ansible/roles/NewRelic_Base/tasks/main.yml': line 12, column 101, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

- name: NewRelic - Replace app_name variable
  replace: dest=/ABC/hybris/newrelic/newrelic.yml regexp='app_name:\s[A-Za-z0-9 ]*' replace="app_name: {{ node }}"
                                                                                                    ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

1 个答案:

答案 0 :(得分:3)

你的例子中的问题是冒号后跟Ansible符号内的空格(带有相同的符号),所以有几种方法可以避免它。

我的建议是使用YAML语法:

tasks:
  - replace:
      dest: ./src
      regexp: 'app_name:\s[A-Za-z0-9 ]*'
      replace: 'app_name: {{ node }}'

对于使用Ansible表示法的提示,请参阅this GitHub thread

示例:

- replace: dest=./src regexp='app_name:\s[A-Za-z0-9 ]*' replace='app_name{{ ":" }} {{ node }}'
- replace: dest=./src regexp='app_name:\s[A-Za-z0-9 ]*' replace='app_name:{{ " " }}{{ node }}'
- replace: "dest=./src regexp='app_name:\s[A-Za-z0-9 ]*' replace='app_name: {{ node }}'"