【发布时间】:2019-05-14 09:56:57
【问题描述】:
我需要将存储在变量中的字符串中的所有 / 替换为 \。
我只是想尽可能简单地通过调试对其进行测试,但无论我如何尝试,我都没有得到将字符替换为字符的预期结果。我认为这可能只是一个单引号/双引号问题,或者可能需要以某种我不知道的方式转义 \。
vars:
- SecGroup: '/stuff/foo/thing'
tasks:
- name: Display modified var
debug:
msg: "{{ SecGroup | replace('/','\') }}"
预期输出:\stuff\foo\thing
尝试不同的输出:
- name: Display modified var
debug:
msg: "{{ SecGroup | replace('/','\') }}"
TASK [Display modified var]
ok: [localhost] => {
"msg": "stufffoothing"
}
- name: Display modified var
debug:
msg: "{{ SecGroup | replace('/','\\') }}"
TASK [Display modified var]
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution."}
- name: Display modified var
debug:
msg: "{{ SecGroup | replace('/','\\\') }}"
TASK [Display modified var]
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution."}
- name: Display modified var
debug:
msg: "{{ SecGroup | replace('/','\\\\') }}"
TASK [Display modified var]
ok: [localhost] => {
"msg": "\\\\stuff\\\\foo\\\\thing"
}
我也尝试恢复引号:
- name: Display modified var
debug:
msg: '{{ SecGroup | replace("/","\") }}'
TASK [Display modified var]
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution."}
我无法解释这个的输出
- name: Display modified var
debug:
msg: '{{ SecGroup | replace("/","\\") }}'
TASK [Display modified var]
ok: [localhost] => {
"msg": "\\\\stuff\\\\foo\\\\thing"
}
【问题讨论】:
-
我很惊讶 ansible 在你使用 ` "{{ SecGroup | replace('/','\') }}" 时没有抛出错误。在双引号标量中,反斜杠可用于转义(这组)[.2/spec.html#id2776092] 的转义字符。如果您查看该列表,您会发现单引号无法转义,这使您的标量无效,并且必须转义反斜杠。但也许 ansible 使用模板来生成 YAML 加载,而不是加载 YAML 并在加载后扩展标量