Why split a long Ansible playbook into several files, and which two ways does Ansible offer to bring that content back in?
Smaller files are easier to manage and can be reused across projects. Content is brought back in either by importing (static) or by including (dynamic).
A playbook that configures a whole server quickly reaches hundreds of lines: users, packages, services, hardening, monitoring. Splitting it helps in two ways. Each file stays short enough to read and review on its own, and a file that does one job (say, "install and start a web server") can be reused by other playbooks and other projects instead of being copied.
There are two levels at which you can split:
- a main playbook that pulls in whole other playbooks, one after another;
- a play that pulls in a list of tasks from a separate task file.
For both, Ansible has the same two mechanisms, and the difference between them is when Ansible reads the file:
Import (import_*) |
Include (include_*) |
|
|---|---|---|
| Kind | static | dynamic |
| When the file is read | once, while the playbook is parsed, before anything runs | during the run, at the moment that task is reached |
Almost every other difference between the two (loops, conditions, handlers, listing tasks) follows from that one point.
Go deeper:
Re-using Ansible artifacts (official docs) — the four reusable artifacts: variables files, task files, playbooks and roles.
Includes and imports: dynamic and static reuse (official docs) — the two mechanisms side by side, in Ansible's own words.