如何在同一个字符串中转义 YAML 中的双引号和单引号 [英] How to escape double and single quotes in YAML within the same string
问题描述
我需要在 ansible playbook 中正确转义单引号和双引号以设置环境变量.这些都不起作用:
I need to properly escape single and double quotes in an ansible playbook in order to set the environment variable. None of this works:
- name: Set environment variable
command: >
export EXTRA_CONFIG="'"{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}"'"
- name: Set environment variable
command: >
export EXTRA_CONFIG=''{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}''
- name: Set environment variable
command: >
export EXTRA_CONFIG=''{\"client\": {\"subscriptions\": [\"DIND-Worker\"], \"cluster\": \"internal\"}}''
看了这个:
http://yaml.org/spec/current.html#id2532720
https://github.com/dotmaster/toYaml/issues/1
我得到的错误信息是:
fatal: [ip.address]: FAILED! => {"changed": false, "cmd": "export 'EXTRA_CONFIG={\"client\":' '{\"subscriptions\":' '[\"DIND-Worker\"],' '\"cluster\":' '\"internal\"}}'", "failed": true, "msg": "[Errno 2] No such file or directory", "rc": 2}
推荐答案
>
开始一个块标量,在这个标量中你根本不需要转义任何东西(并且没有处理任何转义序列).因此,假设您想在类似 JSON 的值周围使用单引号,只需执行以下操作:
>
starts a block scalar, in which you do not need to escape anything at all (and there are no escape sequences processed). So assuming you want single quotes around your JSON-like value, just do:
- name: Set environment variable
command: >
export EXTRA_CONFIG='{"client": {"subscriptions": ["DIND-Worker"], "cluster": "internal"}}'
另请注意,默认情况下折叠标量包括尾随换行符.如果你不想有这个,只需使用 >-
而不是 >
.
Also be aware that a folded scalar by default includes a trailing newline character. If you do not want to have this, just use >-
instead of >
.
这篇关于如何在同一个字符串中转义 YAML 中的双引号和单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!