当变量具有默认值时,Ansible playbook条件失败
给出以下剧本(当变量具有默认值时,Ansible playbook条件失败,ansible,ansible-playbook,ansible-2.x,Ansible,Ansible Playbook,Ansible 2.x,给出以下剧本(deployment.yml): 包含add_host_entries.yml的条件总是失败的,即使上面所有的调试消息都打印某种true(我知道在第一条调试消息中它是一个字符串,而其他两条则是布尔值) 当我省略带有默认值的部分时,将执行add\u host\u entries.yml: when: add_host_entries 不过我需要这个默认值行为,因为它是一个可选值,只在某些阶段设置 其他尝试(未成功) 括号 转换为布尔型 其他来源和资料 以下是重现该问题所需的所有
deployment.yml
):
包含add_host_entries.yml
的条件总是失败的,即使上面所有的调试消息都打印某种true
(我知道在第一条调试消息中它是一个字符串,而其他两条则是布尔值)
当我省略带有默认值的部分时,将执行add\u host\u entries.yml
:
when: add_host_entries
不过我需要这个默认值行为,因为它是一个可选值,只在某些阶段设置
其他尝试(未成功)
括号
转换为布尔型
其他来源和资料
以下是重现该问题所需的所有资源
添加主机条目。yml
库存
呼叫
版本
您尝试有条件地包括剧本。请参阅我关于不同包含类型的回答 问题是,只有在Ansible解析您的剧本之前定义了变量时,这才有效。
但是您尝试将
添加\u主机\u条目
定义为主机级事实(组变量)–这些变量在解析期间尚未定义
如果您使用
-e add\u host\u entries=true调用playbook,您的条件将按预期工作,因为在解析期间已知额外的变量。使用bool
将add\u host\u entries
的字符串值转换为布尔值,然后条件将工作
---
- 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') | bool
实际上,请参见康斯坦丁的答案。他在剧本层面上使用条件是对的。本阶段不考虑存货。
when: (add_host_entries | default('false')) == 'true'
when: add_host_entries|default('false')|bool
---
- 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
---
- 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') | bool