Ansible断言模块报错:'template is boolean'检查失败的解决办法
解决Ansible断言中
template is boolean测试不存在的问题 问题重现
执行命令:
ansible-playbook -i ip "{'template': true}" sample.yml
Playbook代码:
- name: "Verify if the 'template' boolean has been set ?" assert: that: - template is defined - template is boolean fail_msg: "'template' must be defined and be present as a boolean"
错误信息:
MSG: The conditional check 'template is boolean' failed. The error was: template error while templating string: no test named 'boolean'. String: {% if template is boolean %} True {% else %} False {% endif %}
解决方案(不删除template is boolean条件)
方案1:升级Ansible版本
boolean是Ansible 2.10及以上版本新增的Jinja2测试,若使用的Ansible版本低于2.10,直接升级到对应版本即可解决问题,无需修改Playbook代码。
方案2:自定义boolean测试插件
若无法升级Ansible,可通过添加自定义测试插件实现boolean测试功能:
- 在Playbook所在目录创建
filter_plugins文件夹(不存在则新建):
mkdir -p filter_plugins
- 在该文件夹下创建
boolean_test.py文件,内容如下:
from ansible.plugins.test import TestBase class TestBoolean(TestBase): def run(self, var, **kwargs): return isinstance(var, bool)
- 重新执行原Playbook命令,此时
template is boolean条件会被自定义插件处理,可正常生效。
方案3:等价表达式兼容(保留校验逻辑)
若不想升级或添加插件,可通过Jinja2表达式模拟boolean测试的效果,同时保留原校验逻辑:
- name: "Verify if the 'template' boolean has been set ?" vars: is_boolean: "{{ template is defined and (template is sameas true or template is sameas false) }}" assert: that: - template is defined - is_boolean fail_msg: "'template' must be defined and be present as a boolean"
内容的提问来源于stack exchange,提问作者Prabahar S
相关产品推荐
相关产品推荐

