问题
I'm trying to enclose tasks in the block with some when condition. Also some tasks inside this block have additional conditions. The problem is such tasks (with additional conditions) are skipped. Both block's condition and all additional conditions are true.
Below there is a sample play:
- block:
- set_fact:
packages_to_install: "{{ packages_to_install }} + [ '{{ (distrs.stdout | from_json).postgresql }}' ]"
- set_fact:
packages_to_install: "{{ packages_to_install }} + [ '{{ (distrs.stdout | from_json).webserver }}' ]"
when:
- server.webserver is defined
- server.webserver == true
when:
- server is defined
So, postgresql is added to the list of packages, but webserver is not.
According to the docs, all tasks inside the block will be executed after appending the when condition from the block and evaluating it in the task’s context. Maybe it's not just possible in Ansible 2.4 to have enclosed tasks with additional conditions?
回答1:
You should fix the indentation of the when
declarations.
Maybe it's not just possible in Ansible 2.4 to have enclosed tasks with additional conditions?
Ansible 2.4 works ok:
tasks:
- block:
- debug:
msg: "task 1"
- debug:
msg: "task 2"
when: false
- debug:
msg: "task 3"
when: true
when: true
results in:
TASK [debug] **************************************************************************************************
ok: [localhost] => {
"msg": "task 1"
}
TASK [debug] **************************************************************************************************
skipping: [localhost]
TASK [debug] **************************************************************************************************
ok: [localhost] => {
"msg": "task 3"
}
And you can always reorder the keys in block
task for clarity:
tasks:
- when: true
block:
- debug:
来源:https://stackoverflow.com/questions/46543833/additional-conditions-for-tasks-inside-a-block