当变量具有默认值时,Ansible playbook 条件失败 [英] Ansible playbook condition fails when variable has a default value
问题描述
给定以下剧本(deployment.yml
):
---
- name: Debug
hosts: applicationservers
tasks:
- debug: msg="{{add_host_entries | default('false')}}"
- debug: msg="{{add_host_entries | default('false') == 'true'}}"
- debug: msg="Add host entries = {{add_host_entries | default('false') == 'true'}}"
- include: add_host_entries.yml
when: add_host_entries | default('false') == 'true'
包含 add_host_entries.yml
的条件总是失败,即使上述所有调试消息都打印了某种 true
(我知道在第一条调试消息中它是一个字符串,而其他两个结果是布尔值).
The condition to include add_host_entries.yml
always fails, even if all of the above debug messages print some sort of true
(I know that in the first debug message it's a String, whereas the other two result in Booleans).
当我省略有默认值的部分时,会执行add_host_entries.yml
:
When I omit the part with the default value, add_host_entries.yml
will be executed:
when: add_host_entries
不过我需要这个默认值行为,因为它是一个仅在某些阶段设置的可选值.
I need this default value behaviour though, because it's an optional value which is only set on certain stages.
when: (add_host_entries | default('false')) == 'true'
转换为布尔值
when: add_host_entries|default('false')|bool
其他来源和信息
这里是重现问题所需的所有资源.
Other Sources and Information
Here are all the resources needed to reproduce the problem.
---
- name: add_host_entries
hosts: applicationservers
gather_facts: false
tasks:
- debug: msg="Add Host Entries"
库存
[applicationservers]
127.0.0.1
[all:vars]
add_host_entries=true
打电话
markus@lubuntu:~/foobar$ ansible-playbook deployment.yml -i inventory
版本
markus@lubuntu:~/foobar$ ansible --version
ansible 2.1.1.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
markus@lubuntu:~/foobar$ ansible-playbook --version
ansible-playbook 2.1.1.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
推荐答案
您尝试有条件地包含 剧本.请参阅我关于不同包含类型的其他答案.
You try to conditionally include playbook. See my other answer about different include types.
问题是,这仅在之前定义变量时有效.Ansible 解析您的剧本.
但是您尝试将 add_host_entries
定义为主机级事实(组变量)——这些变量在解析时尚未定义.
The thing is, this only works when variable is defined before Ansible parses your playbook.
But you try to define add_host_entries
as host-level fact (group variable) – these variables are not yet defined during parse time.
如果您使用 -e add_host_entries=true
调用您的剧本,您的条件将按预期工作,因为额外变量在解析时是已知的.
If you call your playbook with -e add_host_entries=true
your condition will work as expected, because extra-vars are known during parse time.
这篇关于当变量具有默认值时,Ansible playbook 条件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!