include_tasks 和 import_tasks

include 被deprecated了. 建议使用include_tasksimport_tasks.

例子

x.yml:

- hosts: 127.0.0.1
  gather_facts: False
  tasks:
    - set_fact: mode=1
    - include_tasks: y.yml
      when: mode == "1"

    - set_fact: mode=1
    - import_tasks: y.yml
      when: mode == "1"

y.yml:

- set_fact: mode="2"

- debug:
    msg: >
      Display in only `include_tasks`.
      `include_tasks` does NOT re-evaluate `mode` for every step.
      `import_tasks` DOES re-evaluate condition.

运行ansible-play -b x.yml 后: debug 的message只在include_tasks 里被执行了.

第2个import_tasks中的debug被skip掉了.

因为mode被改变之后, include_tasks 不会重新evaluate mode,import_tasks 会根据变化后的mode值重新evaluate每个task的条件.

示例结果:

TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [include_tasks] **************************************************
included: /root/devops/ansible/y.yml for 127.0.0.1

TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [debug] **********************************************************
ok: [127.0.0.1] => {
    "msg": "Display in only `include_tasks`.
            `include_tasks` does NOT re-evaluate mode for every step.
            `import_tasks` DOES re-evaluate condition\n"
}

TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [debug] **********************************************************
skipping: [127.0.0.1]