Reputation: 3506
I'm running into the silliest issue. I cannot figure out how to test for boolean in an Ansible 2.2 task file.
In vars/main.yml
, I have:
destroy: false
In the playbook, I have:
roles:
- {'role': 'vmdeploy','destroy': true}
In the task file, I have the following:
- include: "create.yml"
when: "{{ destroy|bool }} == 'false'"
I've tried various combinations below:
when: "{{ destroy|bool }} == false"
when: "{{ destroy|bool }} == 'false'"
when: "{{ destroy|bool == false}}"
when: "{{ destroy == false}}"
when: "{{ destroy == 'false'}}"
when: destroy|bool == false
when: destroy|bool == 'false'
when: not destroy|bool
In all the above cases, I still get:
statically included: .../vmdeploy/tasks/create.yml
Debug output:
- debug:
msg: "{{ destroy }}"
---
ok: [atlcicd009] => {
"msg": true
}
The desired result, is that it would skip the include.
Upvotes: 56
Views: 201949
Reputation: 21
In a similar problem that I ran into, I was trying to include_role under my tasks. The roles were to be triggered based on a boolean condition. The below syntax worked for me:
tasks:
- name: trigger role
include_role:
name: "role_path_here"
when:
- call_the_role|bool
call_the_role variable was not declared in this file. Since my problem was more specific to using include_role I took help/ reference from https://github.com/ansible/ansible/issues/18124
Upvotes: 1
Reputation: 111
I have been struggling on this issue too. My problem was, that the variable was not declared inside the script but was given as a extra parameter. In this case you need to convert to bool explicitly
when: destroy|bool
or
when: not destroy|bool
Upvotes: 11
Reputation: 3203
There is no need to use the bool
Jinja filter if the value of the variable is defined under hostvars
.
To cast values as certain types, such as when you input a string as “True” from a vars_prompt and the system doesn’t know it is a boolean value.
So a simple
when: not destroy
should do the trick.
Upvotes: 29
Reputation: 3506
The include kept happening before the when.
So I just made the include dynamic.
---- defaults/main.yml
mode: "create"
---- tasks/main.yml
- include: "{{ mode + '.yml' }}"
Upvotes: -12
Reputation: 68609
To run a task when destroy
is true
:
---
- hosts: localhost
connection: local
vars:
destroy: true
tasks:
- debug:
when: destroy
and when destroy
is false
:
---
- hosts: localhost
connection: local
vars:
destroy: false
tasks:
- debug:
when: not destroy
Upvotes: 94