Additional conditions for tasks inside a block

半城伤御伤魂 提交于 2019-12-02 17:57:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!