Ansible如何将布尔类型转为对应字符串?兼容旧Playbook场景
问题:Ansible 2.4.5中强制cluster_allinone为字符串类型而非布尔类型
为兼容旧版本Inventory逻辑,原有Playbook依赖when: cluster_allinone == "true"的字符串判断,现在需要动态设置cluster_allinone为字符串"true"或"false",但设置后变量总是自动转为布尔类型,尝试to_json、ternary等方法均失败。
原Playbook代码
- name: check node count hosts: all:!gaop-vip-addresses tasks: - name: Get the number of nodes in group2 set_fact: worker_count: "{{ groups['k8s-worker'] | length }}" - debug: var: worker_count - name: set cluster_allinone var set_fact: cluster_allinone: 'true' when: (worker_count | int) == 0 - name: set cluster_allinone var set_fact: cluster_allinone: 'false' when: (worker_count | int) > 0 - debug: var: cluster_allinone - debug: msg: single when: cluster_allinone == "true" - debug: msg: mutil when: cluster_allinone == "false"
尝试过的无效方法
- name: set cluster_allinone var set_fact: temp: 'true' when: (worker_count | int) == 0 - name: set cluster_allinone var set_fact: temp: 'false' when: (worker_count | int) > 0 --- try but fail --- - name: set cluster_allinone var set_fact: cluster_allinone: "{{ temp | to_json }}" - name: set cluster_allinone var set_fact: cluster_allinone: "{{ (worker_count | int) == 0 }}" - name: set cluster_allinone var set_fact: cluster_allinone: "{{ temp | ternary('true', 'false') }}"
当前Ansible版本
ansible 2.4.5.0 config file = /data/ansible.cfg configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /data/ansible/lib/ansible executable location = /data/ansible/bin/ansible python version = 2.7.12 (default, Nov 19 2018, 06:48:02) [GCC 5.4.0 20160609]
解决方案
在Ansible 2.4.5中,set_fact会自动将字符串'true'/'false'转换为布尔类型,解决方法是直接用Jinja2条件表达式生成字符串,避免类型自动转换:
- name: check node count hosts: all:!gaop-vip-addresses tasks: - name: Get the number of nodes in group2 set_fact: worker_count: "{{ groups['k8s-worker'] | length }}" - debug: var: worker_count # 直接用条件表达式生成字符串,避免自动转布尔 - name: Set cluster_allinone as string type set_fact: cluster_allinone: "{{ 'true' if (worker_count | int) == 0 else 'false' }}" - debug: msg: "Type: {{ cluster_allinone | type_debug }}, Value: {{ cluster_allinone }}" - debug: msg: single when: cluster_allinone == "true" - debug: msg: mutil when: cluster_allinone == "false"
说明
- 用Jinja2的
if-else表达式直接生成字符串值,绕过set_fact的自动类型转换逻辑; - 可以用
type_debug过滤器验证变量类型,确保是str而非bool; - 此方法无需修改原有Playbook的判断逻辑,直接覆盖变量即可。
内容的提问来源于stack exchange,提问作者HuaJFrame
相关产品推荐
相关产品推荐

