问题
Given the following 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'
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).
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.
Other Attempts (without success)
Brackets
when: (add_host_entries | default('false')) == 'true'
Casting to boolean
when: add_host_entries|default('false')|bool
Other Sources and Information
Here are all the resources needed to reproduce the problem.
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
Call
markus@lubuntu:~/foobar$ ansible-playbook deployment.yml -i inventory
Versions
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
回答1:
You try to conditionally include playbook. See my other answer about different include types.
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.
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.
回答2:
Use bool
to convert the string value of add_host_entries
into a boolean and then the condition will work.
---
- 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
来源:https://stackoverflow.com/questions/40863809/ansible-playbook-condition-fails-when-variable-has-a-default-value