Lesson 18 / 26

Including and Importing Tasks

Split long task lists and choose between static imports and dynamic includes.

Static or dynamic

To keep files short, move groups of tasks into separate files and pull them in. import_tasks is static: Ansible processes it when it parses the playbook, so tags and when on the import apply to every task inside. include_tasks is dynamic: it is evaluated at run time, which allows loops and variables in the file name but makes --list-tasks and tag inheritance behave differently. Prefer imports for fixed structure and includes when the choice depends on data at run time.

Import vs include

Illustrative snippet. The include picks the file by OS at run time.

- name: Always-present baseline tasks
  ansible.builtin.import_tasks: baseline.yml

- name: OS-specific tasks chosen at run time
  ansible.builtin.include_tasks: "{{ ansible_os_family | lower }}.yml"

Quick check: Which one is evaluated at run time?

  • include_tasks
  • import_tasks
  • Neither
  • Both, always
Answer

include_tasks — include_* is dynamic; import_* is processed when the playbook is parsed.