In this lab, you'll learn how to use include_tasks in Ansible to include separate task files without using any conditions. This basic example will help you understand how to split tasks across multiple files and include them in your playbook.
Estimated Time: 20 minutes
- Use
include_tasksto include task files in a playbook.
- Ansible installed on your ansible machine.
- At least one managed host.
-
Create a Task File Named
common_tasks.yml:-
Create a file named
common_tasks.ymlwith the following content:--- - name: Debug message for common tasks debug: msg: "Running common tasks for all environments"
-
-
Create a Task File Named
env_specific_tasks.yml:-
Create a file named
env_specific_tasks.ymlwith the following content:--- - name: Debug message for environment-specific tasks debug: msg: "Running environment-specific tasks"
-
-
Create a playbook file named
include_tasks_play.ymlwith the following content:--- - name: Include task files example hosts: all gather_facts: no tasks: - name: Include common tasks include_tasks: common_tasks.yml - name: Include environment-specific tasks include_tasks: env_specific_tasks.yml
-
Save the playbook and task files.
-
Run the playbook using the following command:
ansible-playbook include_tasks_play.yml
-
Observe the output. The playbook will include and execute both task files, displaying debug messages from
common_tasks.ymlandenv_specific_tasks.yml.
In this simple lab, you've learned how to use include_tasks to load multiple task files into an Ansible playbook. This method allows you to organize tasks into separate files and reuse them in different playbooks, improving modularity and maintainability. 👏