LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 10 Part 1 of 2
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

Why split a long Ansible playbook into several files, and which two ways does Ansible offer to bring that content back in?

Answer

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:

or press any other key

Question

What exactly does "static" mean for an import and "dynamic" for an include?

Answer

An import is expanded while the playbook is parsed, so it behaves as if the tasks had been pasted in. An include is just one task until the run reaches it; only then is the file read and its tasks added.

Running a playbook has two phases: Ansible first parses the whole playbook into a list of plays and tasks, then executes that list host by host.

Parse phase: an import is read and replaced by its tasks. Run phase: an include stays one task until it is reached, then its when and loop are checked and only then is the file read and run

* Imports are resolved in phase 1, includes in phase 2. *

  • Import (static). During parsing, Ansible opens the imported file and puts its tasks in place of the import line. By the time execution starts, the import has disappeared: the play simply contains those tasks. Nothing that happens during the run can change what was imported.
  • Include (dynamic). During parsing, the include stays a single task. When execution reaches it, Ansible evaluates it like any other task (its when, its loop, its variables for this host), then reads the file and runs the tasks in it. So the result of earlier tasks can decide whether and how the file is included.

A good mental model: import = copy-paste before the run; include = a function call during the run.

Go deeper:

or press any other key