以下是任务:
- name: set value
set_fact:
is_enabled: 'yes'
- name: debug is_enabled value
debug:
var: is_enabled
这会将值打印为“true”而不是“yes”。我尝试将类型转换为字符串。还尝试过:
- name: set value
set_fact:
is_enabled: >
yes
- name: debug is_enabled value
debug:
var: is_enabled
这将打印“yes/n”。
有什么方法可以将变量值设置为“YES”。
正如有关 Ansible Issue #12519 的评论中提到的那样,它似乎是 YAML 的语言功能。根据Ansible set_fact类型转换可以设置DEFAULT_JINJA2_NATIVE
---
- hosts: localhost
become: false
gather_facts: false
vars:
yes1: yes
yes2: 'yes'
yes3: "yes"
tasks:
- name: Set yes
set_fact:
yes4: 'yes'
yes5: "yes"
- name: Show values
debug:
msg: |
yes1 is {{ yes1 | type_debug }} and has value {{ yes1 }}
yes2 is {{ yes2 | type_debug }} and has value {{ yes2 }}
yes3 is {{ yes3 | type_debug }} and has value {{ yes3 }}
yes4 is {{ yes4 | type_debug }} and has value {{ yes4 }}
yes5 is {{ yes5 | type_debug }} and has value {{ yes5 }}
产生的输出
ANSIBLE_JINJA2_NATIVE=True ansible-playbook set_yes_string.yml
[WARNING]: jinja2_native requires Jinja 2.10 and above. Version detected: 2.7.2. Falling back to default.
...
TASK [Show values] *************************
ok: [localhost] =>
msg: |-
yes1 is bool and has value True
yes2 is AnsibleUnicode and has value yes
yes3 is AnsibleUnicode and has value yes
yes4 is AnsibleUnicode and has value yes
yes5 is AnsibleUnicode and has value yes
此外,仅将 bool 设置为 string 过滤器是行不通的。