![](/img/trans.png)
[英]Ansible vars _prompt: playbook fails before value can be assigned to variable
[英]Ansible playbook condition fails when variable has a default value
给出以下playbook( 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
(我知道在第一个调试消息中它是一个String,而另外两个导致布尔值)。
当我省略具有默认值的部分时,将执行add_host_entries.yml
:
when: add_host_entries
我需要这个默认值行为,因为它是一个可选值,仅在某些阶段设置。
when: (add_host_entries | default('false')) == 'true'
when: add_host_entries|default('false')|bool
以下是重现问题所需的所有资源。
add_host_entries.yml
---
- name: add_host_entries
hosts: applicationservers
gather_facts: false
tasks:
- debug: msg="Add Host Entries"
inventory
[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
你试图有条件地包括剧本 。 请参阅我关于不同包含类型的其他答案。
问题是,这仅在 Ansible分析您的剧本之前定义变量时才有效。
但是您尝试将add_host_entries
定义为主机级事实(组变量) - 这些变量在解析add_host_entries
未定义。
如果您使用-e add_host_entries=true
调用您的playbook,您的条件将按预期工作,因为在解析时已知额外值。
使用bool
将add_host_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.