S_lion's Studio

保留特殊字符

字数统计: 238阅读时长: 1 min
2021/11/17 Share

由于Ansible采用Jinja2模板引擎渲染字符串,在需要渲染的时候,如果发现字符串中包含了Jinja2的特殊字符,就会认为这是一个需要渲染的内容。

如下示例:

1
2
3
4
5
6
7
8
9
---
- hosts: localhost
gather_facts: false
tasks:
- name: "测试特殊字符"
debug:
var: pvar
vars:
pvar: !myvar

运行时会报语法错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@slions_pc1 ansible_poc]# ansible-playbook test.yml
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: No JSON object could be decoded

Syntax Error while loading YAML.
could not determine a constructor for the tag '!myvar'

The error appears to be in '/home/ansible_poc/six.yml': line 9, column 15, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

vars:
pvar: !myvar
^ here

想要在定义变量时、指定name属性值时或其它会渲染的地方使用这些Jinja2的特殊符号,需要加上!unsafe标记。这个标记会禁止渲染,保留原始的特殊符号。

1
2
vars:
pvar: !unsafe "!myvar"
CATALOG