Regex 如何在Ansible YAML文件中以字符串形式转义冒号?

Regex 如何在Ansible YAML文件中以字符串形式转义冒号?,regex,ansible,ansible-playbook,Regex,Ansible,Ansible Playbook,我想在安装过程中更改文件/var/www/kibana/config.js中的一行代码 elasticsearch: "http://"+window.location.hostname+":9200" 到 在这里,我尝试使用lineinfle来实现这一点,如下所示 - name: Comment out elasticsearch the config.js to ElasticSearch server lineinfile: dest=/var/www/kibana/conf

我想在安装过程中更改文件/var/www/kibana/config.js中的一行代码

elasticsearch: "http://"+window.location.hostname+":9200"

在这里,我尝试使用lineinfle来实现这一点,如下所示

- name: Comment out elasticsearch the config.js to ElasticSearch server
  lineinfile:
    dest=/var/www/kibana/config.js
    backrefs=true
    regexp="(elasticsearch.* \"http.*)$"
    line="elasticsearch\: \" {{ elasticsearch_URL }}:{{ elasticsearch_port }} \" "
    state=present
我已经将
{{elasticsearch\u URL}}
{{elasticsearch\u port}}
的变量设置为
http://192.168.1.200
9200

以下是我遇到的错误消息:

ERROR: Syntax Error while loading YAML script, /Users/shuoy/devops_workspace/ansible_work/logging-for-openstack/roles/kibana/tasks/Debian.yml
Note: The error may actually appear before this position: line 29, column 25

regexp="(elasticsearch.* \"http.*)$"
line="elasticsearch\: \" {{ elasticsearch_URL }}:{{ elasticsearch_port }} \" "
                    ^

它已经是一根线了;你不必(也不能,如图所示)从里面逃出冒号

line="elasticsearch: \" {{ elasticsearch_URL }}:{{ elasticsearch_port }} \" "

只需将冒号单独用引号引起来-


regexp=“(elasticsearch.\”http.*$”line=“elasticsearch”:“{{elasticsearch\u URL}:{{elasticsearch\u port}}}\”

您需要将整行包含在
”中,其中出现

lineinfile:
'dest=/var/www/kibana/config.js
backrefs=true
regexp="(elasticsearch.* \"http.*)$"
line="elasticsearch\: \ {{ elasticsearch_URL }}:{{ elasticsearch_port }} \ "
state=present'  
请参见以下页面:

foo=bar
是单行指令更合适的格式,但由于您已经用参数跨越了几行,只需将
=
更改为
,它就不会为在字符串中使用冒号而大惊小怪了

- name: Comment out elasticsearch the config.js to ElasticSearch server
  lineinfile:
    dest:     /var/www/kibana/config.js
    backrefs: true
    regexp:   'elasticsearch.* "http.*$'
    line:     'elasticsearch: "{{ elasticsearch_URL }}:{{ elasticsearch_port }}"'
    state:    present

在任何情况下,无论您可能有多少嵌套引号,都可以使用的解决方案是通过Jinja2表达式输出冒号,该表达式仅以字符串形式返回冒号,而不必强制您在整件事情周围添加更多引号(这可能会因您要写入的行而变得棘手,甚至不可能):

{{ ":" }}
或者在您的整个产品系列中:

line="elasticsearch\: \" {{ elasticsearch_URL }}{{ ":" }}{{ elasticsearch_port }} \" "

我发现在所有情况下都能始终如一地发挥作用的是一个变量。例如,
vars/main.yml

fw_zone_str: 'Error: NAME_CONFLICT: new_zone():'
failed_when: fw_zone_str not in fw_new_zone.stderr
任务/foo.yml
中:

fw_zone_str: 'Error: NAME_CONFLICT: new_zone():'
failed_when: fw_zone_str not in fw_new_zone.stderr

非常感谢!被接受的答案对我来说并不是那么简单,但它让shell脚本几乎无法阅读:
awk-F{:“}}”/[^{{:“}}]*{{:“}}}\$/{print”“$1{:“}”:“}”$2}'/tmp/shadow
这个解决方案的问题是,当我在when语句中使用它时,它会发出这个警告:
[warning]:条件语句不应包括jinja2模板分隔符,如{{}或{%}。找到:('versionlock delete{{:“}}没有匹配项'不在第三方_unlock.stderr中)
。是,即使设置了
warn:false