12-Day5-1-include_tasksAndimport_tasks
Day 5: Lab Exercise - Using Include and Import for Task and Play Segregation
Objective:
This lab introduces participants to modularizing Ansible playbooks using the include_tasks, import_tasks, and import_playbook directives. Participants will learn how to segregate tasks and plays to improve playbook reusability, readability, and maintainability.
Lab 1.1: Using include_tasks for Dynamic Task Inclusion
include_tasks for Dynamic Task InclusionScenario:
Dynamically include tasks based on a variable (e.g., install Apache on one host group and Nginx on another).
Steps:
Create Task Files:
Create
~/day5/tasks/install_apache.yaml:- name: Install Apache yum: name: httpd state: present - name: Start and enable Apache service: name: httpd state: started enabled: trueCreate
~/day5/tasks/install_nginx.yaml:- name: Install Nginx yum: name: nginx state: present - name: Start and enable Nginx service: name: nginx state: started enabled: true
Create the Playbook:
Save as
~/day5/include_tasks_playbook.yaml:- name: Include Tasks Dynamically hosts: all vars: web_server: apache tasks: - name: Dynamically include tasks based on web_server variable include_tasks: "tasks/install_{{ web_server }}.yaml"
Run the Playbook:
ansible-playbook ~/day5/include_tasks_playbook.yamlExercise:
Change the
web_servervariable tonginxand re-run the playbook.
Lab 1.2: Using import_tasks for Static Task Inclusion
import_tasks for Static Task InclusionScenario:
Include static tasks for system setup (e.g., update packages and install basic tools).
Steps:
Create Task Files:
Create
~/day5/tasks/update_system.yaml:Create
~/day5/tasks/install_tools.yaml:
Create the Playbook:
Save as
~/day5/import_tasks_playbook.yaml:
Run the Playbook:
Lab 1.3: Using import_playbook for Playbook Segregation
import_playbook for Playbook SegregationScenario:
Split a large playbook into smaller modular playbooks and include them.
Steps:
Create Smaller Playbooks:
Save as
~/day5/playbooks/webserver_setup.yaml:Save as
~/day5/playbooks/dbserver_setup.yaml:
Create the Master Playbook:
Save as
~/day5/import_playbook_master.yaml:
Run the Master Playbook:
Exercise:
Modify the
dbserver_setup.yamlplaybook to include tasks for creating a database and a user.
Optional Lab 1.4: Dynamic Web and Database Role Assignment
Use
group_varsor inventory variables to dynamically assignweb_serveranddb_serverroles.Create a playbook to assign tasks based on these variables.
Key Learning Points:
include_tasksvs.import_tasks:include_tasksallows dynamic task inclusion during runtime.import_tasksincludes tasks statically during playbook parse time.
Modular Playbooks with
import_playbook:Segregating large playbooks into smaller, reusable components.
Improved Maintainability:
Modularization leads to better organization and easier troubleshooting.
These exercises introduce participants to modular playbook designs, preparing them for advanced role management and large-scale deployments.
Last updated