Aurora Store's playbooks are now clean, but inside the roles it's a different story: roles/nginx/tasks/main.yml is a long list mixing installation, configuration, site, service and firewall, and the three ufw tasks repeat the same condition. Ansible lets you split a task list into several files and combine them in two ways: by importing them (statically, when the playbook is loaded) or by including them (dynamically, during the run). The difference looks like a technical detail, but it changes how conditions, loops, tags and tools such as --list-tasks behave. In this lesson you'll learn import_tasks and include_tasks, their equivalents for roles (import_role and include_role), you'll revisit import_playbook, you'll split the tasks of the nginx and postgresql roles into files with a clear responsibility and you'll make postgresql load its internal variables according to the server's distribution.
Contents
- Why split tasks into files
import_tasks: static importinclude_tasks: dynamic inclusion- Static versus dynamic: table of differences
whenwith import and with include- Loops: only with include
- Tags: inheritance and
apply import_roleandinclude_roleimport_playbook: a reminder- Practice: splitting the
nginxrole - Practice: splitting the
postgresqlrole - Variables per distribution:
include_varsandfirst_found - Verifying and saving the work
- Why split tasks into files
A task file of 80 or 100 lines is still readable, but roles grow: the PostgreSQL one will end up managing backups, extensions, replicas… Splitting tasks into files gives you:
- Readability:
tasks/main.ymlbecomes an index ("install, configure, site, service, firewall") and each file has one responsibility. - Grouped conditions: a single condition for a whole block of tasks, instead of repeating it on each one.
- Partial reuse: another playbook can run just one part of the role (for example, only the installation).
- Loops over several tasks: repeating a group of tasks for each item in a list.
- Per-system variants: loading some files or others depending on the distribution.
An additional task file has the same format as tasks/main.yml: a list of tasks with no hosts: and no tasks:. Inside a role it's kept in tasks/ and referenced by its name (install.yml); Ansible looks for it in the role's tasks/ directory. Outside a role, the path is relative to the playbook.
import_tasks: static import
import_tasks: static importansible.builtin.import_tasks inserts the tasks from another file when the playbook is loaded, before anything starts running. The result is exactly the same as if you had written those tasks at that point:
Characteristics:
- The
import_taskstask disappears: in the output and in--list-tasksyou'll only see the imported tasks. - Since everything is resolved before running,
--syntax-checkalso checks the imported files, and--list-tasksshows them. - The file name can only use variables known before running (inventory, the play's
vars:,-e), not facts or registered variables. - The keywords you put on the import (
when,tags,become…) are copied to each imported task.
include_tasks: dynamic inclusion
include_tasks: dynamic inclusionansible.builtin.include_tasks loads the file during the run, when it reaches that task, and for each host:
- name: Configure the firewall
ansible.builtin.include_tasks: firewall.yml
when: nginx_firewall_enabledCharacteristics:
- The inclusion is just another task: it appears in the output (
included: .../firewall.yml for web1, web2), counts asokin thePLAY RECAPand can be skipped (skipping). - Its keywords (
when,tags…) apply to the inclusion itself, not to the tasks in the file: if the condition is false, the file isn't even loaded. - Since it's resolved at run time, the file name can use any variable, including facts:
include_tasks: "setup-{{ ansible_facts['os_family'] }}.yml". - It supports loops (
loop). - In exchange, Ansible doesn't know its content in advance:
--list-tasksdoesn't show the included tasks and--syntax-checkdoesn't check them.
- Static versus dynamic: table of differences
| Aspect | import_* (static) |
include_* (dynamic) |
|---|---|---|
| When it's processed | When the playbook is loaded | During the run, when the task is reached |
| Variables in the file name | Only those known at the start (inventory, play, -e) |
Any, including facts and registered variables |
when |
Copied to each imported task and evaluated on each one | Evaluated once, on the inclusion |
loop |
Not allowed | Allowed |
tags |
Inherited by all the imported tasks | Only affect the inclusion (use apply to pass them on) |
--list-tasks / --list-tags |
Show the imported tasks | Only show the inclusion task |
--start-at-task |
Can start at an imported task | Doesn't find the included tasks |
--syntax-check |
Checks the imported files | Doesn't check them |
| Handlers | Each imported handler can be notified by its name | Notifying an inclusion runs the whole file (Lesson 5.1) |
| In the output | The import doesn't appear | included: file for hosts appears |
Rule of thumb:
- Use
import_tasksby default, for organizing: it's predictable and the tools see everything. - Use
include_taskswhen you need something only the dynamic approach allows: a loop, a file name that depends on facts, or evaluating a condition just once for a whole block.
when with import and with include
when with import and with includeThe difference in conditions deserves an example, because it produces errors that are hard to understand. In ~/aurora-infra, create a test task file, mark.yml:
---
- name: Mark as done
ansible.builtin.set_fact:
demo_done: true
- name: Show a message
ansible.builtin.debug:
msg: Second task runAnd a test playbook, demo-import.yml:
---
- name: Try out the condition with import_tasks
hosts: web1
gather_facts: false
tasks:
- name: Import the test tasks
ansible.builtin.import_tasks: mark.yml
when: not (demo_done | default(false))TASK [Mark as done] ************************************************************
ok: [web1]
TASK [Show a message] **********************************************************
skipping: [web1]The condition was copied to both tasks. The first one runs (demo_done doesn't exist yet) and creates the variable; when it reaches the second, the condition is evaluated again, it's now false and the task is skipped. Change import_tasks to include_tasks and repeat:
TASK [Import the test tasks] ***************************************************
included: /home/student/aurora-infra/mark.yml for web1
TASK [Mark as done] ************************************************************
ok: [web1]
TASK [Show a message] **********************************************************
ok: [web1] =>
msg: Second task runWith include_tasks, the condition was evaluated once, before loading the file, and then all its tasks ran. Neither behavior is "the correct one": you must choose the one you need. If the condition can change inside the block and you want to decide just once, use include_tasks.
Delete the test files:
- Loops: only with include
import_tasks doesn't support loop:
With include_tasks you can repeat a group of tasks for each item in a list, something a normal loop (a single task) can't do. For example, if for each PostgreSQL database you had to create the database, enable an extension on it and grant privileges, you could write a database.yml file with those three tasks and include it like this:
- name: Configure each database
ansible.builtin.include_tasks: database.yml
loop: "{{ postgresql_databases }}"
loop_control:
loop_var: postgresql_database
label: "{{ postgresql_database.name }}"Inside database.yml, each task would use postgresql_database.name and postgresql_database.owner. The key detail is loop_var (Lesson 3.6): if the included file in turn had tasks with loop, both would use item and one would overwrite the other; giving the outer loop variable its own name avoids the conflict, and also makes the code easier to understand. (This is an illustrative example: Aurora's role doesn't need it, because each database is handled with a single task.)
- Tags: inheritance and
apply
applyTags (tags) let you run only part of a playbook with --tags; you'll study them in depth in Lesson 5.6. Here it's enough to know how they combine with imports and inclusions:
# The three tasks in firewall.yml get the "firewall" tag.
- name: Configure the firewall
ansible.builtin.import_tasks: firewall.yml
tags: firewall
# Only the inclusion has the tag; the included tasks don't.
- name: Configure the firewall
ansible.builtin.include_tasks: firewall.yml
tags: firewall
# The inclusion has the tag and, with apply, so do its tasks.
- name: Configure the firewall
ansible.builtin.include_tasks:
file: firewall.yml
apply:
tags: firewall
tags: firewallWith the second form, ansible-playbook webservers.yml --tags firewall would run the inclusion but none of its tasks, because they don't have the tag. It's one of the most frequent surprises with include_tasks. The third form solves it: tags on the inclusion makes it run, and apply copies the tags to the included tasks.
import_role and include_role
import_role and include_roleThe same two philosophies exist for roles, which you can use as tasks inside a list:
tasks:
- name: Install nginx without configuring any site
ansible.builtin.import_role:
name: nginx
tasks_from: install
- name: Apply the website role only if requested
ansible.builtin.include_role:
name: aurora_app
when: aurora_deploy_app | default(true) | boolUseful parameters of both modules:
| Parameter | Meaning |
|---|---|
name |
Name of the role |
tasks_from |
File in tasks/ to start from, instead of main (without .yml) |
vars_from, defaults_from, handlers_from |
Same, for vars/, defaults/ and handlers/ |
apply |
include_role only: keywords (tags, become…) applied to the role's tasks |
public |
include_role only: if true, the role's variables remain visible to the rest of the play (by default they aren't) |
allow_duplicates |
Whether the role can run even if it has already been applied (true by default) |
Compared with the roles: keyword:
roles: |
import_role |
include_role |
|
|---|---|---|---|
| Where it's written | Play section | As a task | As a task |
| When it runs | Before tasks: |
Wherever the task is | Wherever the task is |
| Nature | Static | Static | Dynamic |
when |
Copied to each task | Copied to each task | Evaluated once |
loop |
No | No | Yes |
| Deduplication | Yes | No (by default) | No (by default) |
tasks_from deserves a warning: if you run only part of a role, the tasks in the earlier parts don't run. If one of them loads variables (as you'll do in section 12 with include_vars), the part you run could find them undefined.
In Aurora, the roles: keyword remains the main approach: it's the most readable way to express "these servers get these roles". import_role and include_role are tools for specific cases, such as the rolling deployments in Lesson 5.7.
import_playbook: a reminder
import_playbook: a reminderYou've been using ansible.builtin.import_playbook in site.yml since Lesson 3.4. It belongs to the same family:
- It's static: Ansible loads all the imported playbooks before starting.
- It goes at play level, not inside
tasks:. - There's no
include_playbook: playbooks can only be imported. - It supports
whenandtags, which apply to all the imported plays.
Summary of the family:
| Level | Static | Dynamic |
|---|---|---|
| Playbooks | import_playbook |
— |
| Tasks | import_tasks |
include_tasks |
| Roles | import_role (and roles:) |
include_role |
| Variables | vars_files (play) |
include_vars (task) |
- Practice: splitting the
nginx role
nginx roleOrganize roles/nginx/tasks/ into five files. Create roles/nginx/tasks/install.yml:
---
- name: Install nginx
ansible.builtin.apt:
name: "{{ nginx_package }}"
state: present
update_cache: true
cache_valid_time: 3600roles/nginx/tasks/configure.yml (global web server configuration):
---
- name: Publish the gzip compression configuration
ansible.builtin.copy:
src: gzip.conf
dest: "{{ nginx_conf_d_dir }}/gzip.conf"
owner: root
group: root
mode: "0644"
register: nginx_gzip_configroles/nginx/tasks/site.yml (the site the role serves; don't confuse it with the site.yml playbook at the root of the project: this is a task file inside roles/nginx/tasks/):
---
- name: Configure the site in nginx
ansible.builtin.copy:
dest: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
owner: root
group: root
mode: "0644"
content: |
# Managed by Ansible (aurora-infra). Do not edit by hand.
server {
listen {{ nginx_port }} default_server;
listen [::]:{{ nginx_port }} default_server;
server_name {{ nginx_server_name }};
root {{ nginx_root }};
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
register: nginx_site_config
- name: Enable the site
ansible.builtin.file:
src: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
dest: "{{ nginx_sites_enabled_dir }}/{{ nginx_site_name }}"
state: link
register: nginx_site_enabled
- name: Disable the default nginx site
ansible.builtin.file:
path: "{{ nginx_sites_enabled_dir }}/default"
state: absent
when: nginx_remove_default_site
register: nginx_default_siteroles/nginx/tasks/service.yml:
---
- name: Ensure nginx is started and enabled
ansible.builtin.systemd_service:
name: "{{ nginx_service }}"
state: started
enabled: true
- name: Reload nginx if its configuration has changed (temporary)
ansible.builtin.systemd_service:
name: "{{ nginx_service }}"
state: reloaded
when: >-
nginx_gzip_config is changed or
nginx_site_config is changed or
nginx_site_enabled is changed or
nginx_default_site is changedroles/nginx/tasks/firewall.yml, now without the repeated conditions:
---
- name: Allow SSH through the firewall
community.general.ufw:
rule: allow
name: OpenSSH
- name: Allow HTTP through the firewall
community.general.ufw:
rule: allow
port: "{{ nginx_port }}"
proto: tcp
- name: Enable the firewall
community.general.ufw:
state: enabledAnd replace roles/nginx/tasks/main.yml with the role's index:
---
- name: Install nginx
ansible.builtin.import_tasks: install.yml
- name: Configure nginx
ansible.builtin.import_tasks: configure.yml
- name: Configure the site
ansible.builtin.import_tasks: site.yml
- name: Manage the service
ansible.builtin.import_tasks: service.yml
- name: Configure the firewall
ansible.builtin.include_tasks: firewall.yml
when: nginx_firewall_enabledDecisions:
- The first four parts are imported: they always run, and this way
--list-tasks,--syntax-checkand--start-at-taskstill see all their tasks. - The firewall is included with the condition: it's evaluated once and, if
nginx_firewall_enabledis false, the file isn't even loaded and doesn't clutter the output with threeskippinglines. The condition is now written only once. - The variables registered in
configure.ymlandsite.ymlare used inservice.yml: registered variables belong to the host, not to the file, so they're available in any later task. - The service goes after the configuration so that the temporary reload sees all the changes. In Lesson 5.1 this file will be reduced to its first task, and the reload will be a handler.
- Practice: splitting the
postgresql role
postgresql roleSplit roles/postgresql/tasks/main.yml into four files. You'll complete install.yml in section 12; for now, it only contains the installation:
---
- name: Install PostgreSQL and the Ansible module dependencies
ansible.builtin.apt:
name: "{{ postgresql_packages }}"
state: present
update_cache: true
cache_valid_time: 3600roles/postgresql/tasks/configure.yml:
---
- name: Configure the PostgreSQL parameters
ansible.builtin.copy:
dest: "{{ postgresql_config_dir }}/conf.d/{{ postgresql_conf_name }}.conf"
owner: postgres
group: postgres
mode: "0644"
content: |
# Managed by Ansible (aurora-infra). Do not edit by hand.
listen_addresses = '{{ postgresql_listen_addresses }}'
port = {{ postgresql_port }}
max_connections = {{ postgresql_max_connections }}
shared_buffers = {{ postgresql_shared_buffers }}
register: postgresql_config
- name: Restart PostgreSQL if its configuration has changed (temporary)
ansible.builtin.systemd_service:
name: "{{ postgresql_service }}"
state: restarted
when: postgresql_config is changed
- name: Ensure PostgreSQL is started and enabled
ansible.builtin.systemd_service:
name: "{{ postgresql_service }}"
state: started
enabled: trueroles/postgresql/tasks/users.yml (users and databases, in that order):
---
- name: Create the PostgreSQL users
community.postgresql.postgresql_user:
name: "{{ item.name }}"
state: present
become_user: postgres
loop: "{{ postgresql_users }}"
loop_control:
label: "{{ item.name }}"
- name: Create the databases
community.postgresql.postgresql_db:
name: "{{ item.name }}"
owner: "{{ item.owner }}"
state: present
become_user: postgres
loop: "{{ postgresql_databases }}"
loop_control:
label: "{{ item.name }}"roles/postgresql/tasks/access.yml (access control):
---
- name: Allow the clients to access the database
community.postgresql.postgresql_pg_hba:
dest: "{{ postgresql_config_dir }}/pg_hba.conf"
contype: host
databases: "{{ postgresql_hba_database }}"
users: "{{ postgresql_hba_user }}"
address: "{{ item }}/32"
method: "{{ postgresql_hba_method }}"
state: present
loop: "{{ postgresql_hba_clients }}"
register: postgresql_hba
- name: Reload PostgreSQL if access control has changed (temporary)
ansible.builtin.systemd_service:
name: "{{ postgresql_service }}"
state: reloaded
when: postgresql_hba is changedAnd roles/postgresql/tasks/main.yml:
---
- name: Install PostgreSQL
ansible.builtin.import_tasks: install.yml
- name: Configure PostgreSQL
ansible.builtin.import_tasks: configure.yml
- name: Manage users and databases
ansible.builtin.import_tasks: users.yml
- name: Manage access control
ansible.builtin.import_tasks: access.ymlThe order of the tasks is exactly the same as before; only their organization has changed.
- Variables per distribution:
include_vars and first_found
include_vars and first_foundThe internal variables of the postgresql role (postgresql_packages, postgresql_service, postgresql_config_dir) are the Ubuntu/Debian ones. On Rocky Linux, for example, the package is called postgresql-server and the configuration is in /var/lib/pgsql/data. The standard technique for making a role support several distributions is:
- A variables file per distribution or family in
vars/. - A task at the beginning that loads the right one according to the server's facts.
The ansible.builtin.include_vars module loads variables from a YAML file during the run (with a high precedence: above the inventory and vars/main.yml). To choose the file, you use the first_found lookup, which receives a list of candidates and returns the first one that exists.
Move the internal variables to a family file. Create roles/postgresql/vars/Debian.yml:
---
# Internal variables of the postgresql role for the Debian family (Debian, Ubuntu).
postgresql_packages:
- postgresql
- python3-psycopg2 # required by the community.postgresql modules
- acl # lets Ansible become the postgres user
postgresql_service: postgresql
postgresql_config_dir: "/etc/postgresql/{{ postgresql_version }}/main"Delete roles/postgresql/vars/main.yml, which is left with no content:
And add to the beginning of roles/postgresql/tasks/install.yml:
---
- name: Load the distribution variables
ansible.builtin.include_vars: "{{ lookup('ansible.builtin.first_found', postgresql_os_vars) }}"
vars:
postgresql_os_vars:
files:
- "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_major_version'] }}.yml"
- "{{ ansible_facts['os_family'] }}.yml"
paths:
- vars
- name: Install PostgreSQL and the Ansible module dependencies
ansible.builtin.apt:
name: "{{ postgresql_packages }}"
state: present
update_cache: true
cache_valid_time: 3600How it works:
postgresql_os_varsis a task variable (it only exists in this task) with the list of candidates, from the most specific to the most general. Ondb1the facts aredistribution = Ubuntu,distribution_major_version = 24andos_family = Debian, so the candidates areUbuntu-24.ymlandDebian.yml.paths: [vars]says where to look for them: in the role'svars/directory.first_foundreturns the path of the first one that exists. Since there's noUbuntu-24.yml, it returnsDebian.yml, andinclude_varsloads it.- If one day a specific version needed other values, creating
vars/Ubuntu-26.ymlwould be enough: it would be more specific and would beatDebian.ymlwithout touching the tasks. - The loaded variables belong to the host and are available in all the later tasks of the play (
configure.yml,users.yml,access.yml).
What if the server belongs to a family with no file? first_found fails with a clear error:
fatal: [db9]: FAILED! =>
msg: '... The lookup plugin ''ansible.builtin.first_found'' failed: No file was found when using first_found.'(The text surrounding the message varies between ansible-core versions, but it always ends with "No file was found when using first_found".) It's exactly what you want: a role that doesn't support a system should fail at the start, not halfway through the configuration. This fulfills what you left pending in Lesson 4.3: galaxy_info.platforms documents the platforms, and first_found enforces them. To add Rocky Linux support, you'd have to create vars/RedHat.yml:
---
# Illustrative example: NOT part of Aurora's role.
postgresql_packages:
- postgresql-server
- python3-psycopg2
postgresql_service: postgresql
postgresql_config_dir: /var/lib/pgsql/data…and quite a bit more: the installation uses dnf instead of apt, the cluster has to be initialized, and the conf.d directory isn't enabled by default. That's why Aurora doesn't include it: a variables file on its own doesn't make a role work on another distribution, and it's better to fail clearly than to pretend to support something that hasn't been tested.
You'll also find this older, equivalent form in many roles:
- name: Load the distribution variables
ansible.builtin.include_vars: "{{ item }}"
with_first_found:
- "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_major_version'] }}.yml"
- "{{ ansible_facts['os_family'] }}.yml"Inside a role, include_vars looks for relative files in vars/, so there's no need to specify the path. It works the same, but the lookup form is the recommended one today, just like loop versus with_* (Lesson 3.6).
The same technique works for different tasks per system: include_tasks: "install-{{ ansible_facts['os_family'] }}.yml". Here include_tasks is mandatory, because the file name depends on a fact that doesn't exist when the playbook is loaded.
- Verifying and saving the work
Check the web servers' task list:
play #1 (webservers): Configure the Aurora Store web servers TAGS: []
tasks:
nginx : Install nginx TAGS: []
nginx : Publish the gzip compression configuration TAGS: []
nginx : Configure the site in nginx TAGS: []
nginx : Enable the site TAGS: []
nginx : Disable the default nginx site TAGS: []
nginx : Ensure nginx is started and enabled TAGS: []
nginx : Reload nginx if its configuration has changed (temporary) TAGS: []
nginx : Configure the firewall TAGS: []
aurora_app : Create the web root directory TAGS: []
...The imported tasks appear one by one; the firewall appears as one task, the inclusion, because its content will only be known at run time. Run the whole infrastructure:
TASK [postgresql : Load the distribution variables] ****************************
ok: [db1]
...
TASK [nginx : Configure the firewall] ******************************************
included: /home/student/aurora-infra/roles/nginx/tasks/firewall.yml for web1, web2
TASK [nginx : Allow SSH through the firewall] **********************************
ok: [web1]
ok: [web2]
...
PLAY RECAP *********************************************************************
db1 : ok=... changed=0 unreachable=0 failed=0 ...
web1 : ok=... changed=0 unreachable=0 failed=0 ...
web2 : ok=... changed=0 unreachable=0 failed=0 ...changed=0 once more. The number of ok has changed (the inclusion and the variable loading count as tasks), but no server has changed. Save the work:
git add roles/nginx roles/postgresql
git commit -m "nginx and postgresql roles split into files; postgresql variables per distribution"Structure of the two roles:
roles/nginx/
├── README.md
├── defaults/main.yml
├── files/gzip.conf
├── meta/main.yml
├── tasks/
│ ├── main.yml ← index: import ×4 + include (firewall)
│ ├── install.yml
│ ├── configure.yml
│ ├── site.yml
│ ├── service.yml
│ └── firewall.yml
└── vars/main.yml
roles/postgresql/
├── README.md
├── defaults/main.yml
├── meta/main.yml
├── tasks/
│ ├── main.yml ← index: import ×4
│ ├── install.yml ← include_vars + first_found
│ ├── configure.yml
│ ├── users.yml
│ └── access.yml
└── vars/Debian.ymlCommon Mistakes and Tips
You cannot use loops on 'import_tasks' statements: switch toinclude_tasks.- Fact variables in the file name of an
import_tasks: it fails because the facts don't exist yet when the playbook is loaded. Useinclude_tasks. - Included tasks that don't run with
--tags: the tags of aninclude_tasksaren't inherited. Useapply, orimport_tasksif you don't need anything dynamic. --start-at-taskthat "can't find" a task: it's inside aninclude_tasks. Start at an earlier task or use imports.- An
import_taskscondition that skips tasks "for no reason": the condition is evaluated on each task, and some earlier task in the file has changed a variable it depends on. Useinclude_tasksif you want to decide just once. itemoverwritten in nested loops: aninclude_taskswithloopwhose file contains anotherloop. Useloop_control.loop_varin the outer loop.- Using
include_varsfor configurable parameters: its precedence is higher than the inventory's, so the user couldn't change them. Reserve it for internal variables, such as the per-distribution ones. - Tip: a simple rule for your roles:
tasks/main.ymlcontains only imports and inclusions, each with a name that describes the phase. That way, openingmain.ymlmeans reading the role's index.
Exercises
Exercise 1: Splitting the common role
Split roles/common/tasks/main.yml into files with one responsibility each (packages, time zone, users, welcome message and local facts) and turn main.yml into an index of imports. Verify with --list-tasks and with site.yml that the result is changed=0.
Exercise 2: Packages per family with include_tasks
In common, the two package installation tasks use when with os_family. Rewrite them with two files, packages-Debian.yml and packages-RedHat.yml, and a single inclusion whose file name depends on the os_family fact. Why doesn't import_tasks work here? What would happen on a server from a family with no file?
Exercise 3: Import or include?
State what you would use in each case and why:
- Organizing a role's tasks into
install.yml,configure.ymlandservice.yml, which always run. - Repeating three tasks (create a directory, publish a file, create a link) for each site in an
nginx_siteslist. - Running a backup task file only if the local fact
ansible_local['aurora']['general']['env']isproduction, evaluating the condition just once. - Being able to start the run with
--start-at-taskat any task of the role.
Solutions
Exercise 1. For example: packages.yml (the two package tasks), timezone.yml, users.yml (users and administrator privileges), motd.yml and facts.yml (directory, file and re-read). roles/common/tasks/main.yml:
---
- name: Install the common packages
ansible.builtin.import_tasks: packages.yml
- name: Configure the time zone
ansible.builtin.import_tasks: timezone.yml
- name: Manage the team users
ansible.builtin.import_tasks: users.yml
- name: Configure the welcome message
ansible.builtin.import_tasks: motd.yml
- name: Publish the local facts
ansible.builtin.import_tasks: facts.ymlWith imports, --list-tasks shows the same nine tasks as before and site.yml gives changed=0. (If you do this exercise, the role works the same as the course's reference role: the rest of the lessons don't depend on how its tasks are distributed.)
Exercise 2. roles/common/tasks/packages-Debian.yml:
---
- name: Install the common packages (Debian family)
ansible.builtin.apt:
name: "{{ common_packages }}"
state: present
update_cache: true
cache_valid_time: 3600roles/common/tasks/packages-RedHat.yml:
---
- name: Install the common packages (Red Hat family)
ansible.builtin.dnf:
name: "{{ common_packages }}"
state: presentAnd instead of the two original tasks:
- name: Install the common packages
ansible.builtin.include_tasks: "packages-{{ ansible_facts['os_family'] }}.yml"import_tasks doesn't work because the file name depends on a fact, which doesn't exist when Ansible loads the playbook. On a server from a family with no file (for example, Suse), the inclusion would fail because packages-Suse.yml doesn't exist: a clear, early failure, as with first_found. The advantage over the when version: there's no longer a skipping task on each server.
Exercise 3.
import_tasks: they always run, and this way the tools (--list-tasks,--syntax-check,--start-at-task) see all the tasks.include_taskswithloop(andloop_control.loop_var, for examplenginx_site): it's the only way to repeat a group of tasks.include_taskswithwhen: the condition is evaluated just once, on the inclusion. Withimport_tasksit would be evaluated on each task.import_tasks:--start-at-taskdoesn't find dynamically included tasks.
Conclusion
You've learned the two ways of reusing tasks in Ansible: static import (import_tasks, import_role, import_playbook), which is resolved when the playbook is loaded, copies its keywords to each task and is visible to all the tools, and dynamic inclusion (include_tasks, include_role, include_vars), which is resolved at run time, evaluates its condition just once, supports loops and file names based on facts, but doesn't pass on tags without apply. You've applied it to Aurora Store: nginx and postgresql now have a tasks/main.yml that is an index of phases (install, configure, site, service and a firewall included with a single condition; install, configure, users and access), and postgresql loads its internal variables from vars/Debian.yml with include_vars and first_found, so it would fail clearly on an unsupported distribution. The roles are now well organized on the inside, but there are still things that only exist in the head of whoever wrote them: that aurora_app needs nginx, which variables are mandatory, what type of value each one expects. In the next lesson, Role Dependencies and Argument Validation, you'll declare those relationships in meta/main.yml, automatically validate the variables with meta/argument_specs.yml and document the roles.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
