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

标签 regex replace ansible

我需要用 app_name: <anything> 替换字符串至app_name: {{ node }} .

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

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

错误消息:

[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 }}"

最佳答案

您的示例中的问题是 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 }}'"

关于regex - 使用 Ansible 中的替换模块用正则表达式替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41697439/

相关文章:

php - 正则表达式中的双加号

javascript - 如何使字母的赌场式增量?

JavaScript - 用 "no-js"类替换 "js"类不起作用?

jenkins - 如何通过命令行在jenkins中设置jnlp端口?

postgresql - Ansible docker postgres 卷

ansible - Ansible 中按自然字母数字顺序对列表进行排序

c# - Regex.IsMatch() 无法识别转义序列?

java - 正则表达式捕获组混淆

php - 如何使用正则表达式创建循环?

powershell - 如何在powershell中[int]添加[string]正则表达式替换?