Ansible is a powerful automation tool that allows us to define and run the multi-tier application environments. One of the ways that Ansible manages this complexity is through its role-based organization which allows for code reusability.
In this post, we will learn how to use the include_role directive in Ansible. This directive provides a mechanism to dynamically load and execute the roles within playbooks, tasks, or other roles.
Ansible Include_Role
The include_role module allows us to load and execute a specified role as a task dynamically.
The module supports various parameters as expressed in the following:
Allow_duplicates – It is used to override the role’s metadata setting to allow using a role more than once with the same parameters.
Apply – It accepts a has of task keywords that are applied to all the tasks that are defined in the role.
Defaults_from – It specifies the file to load from a role’s defaults/directory.
Name – It specifies the name of the role to be executed.
Tasks_from – It specifies the file to load from the role’s tasks/directory.
The given parameters are some common parameters when working with the include_role module. You can refer to the docs to learn more.
The following shows a basic syntax of the include_role module:
include_role:
name: my_role
Let us explore some examples on how to work with this module.
Basic Usage:
The following shows a basic example on how to include a role:
- hosts: all
tasks:
- name: Include a basic role
include_role:
name: setup
The given example playbook includes and runs the setup role.
Include the Role with Variables
Ansible roles have pre-defined variables that we can overwrite as necessary. An example is as follows:
- hosts: all
tasks:
- name: Include role with vars
include_role:
name: user_setup
vars:
username: linuxhint
user_group: root
In this case, we execute the user_setup role with the defined username and the user_group variables.
Conditional Role Inclusion
Ansible also allows us to conditionally include the roles based on certain conditions as demonstrated in the following example:
- hosts: all
tasks:
- name: Include role for Linux machines only
include_role:
name: linux_setup
when: ansible_os_family == "Debian" or ansible_os_family == "RedHat"
We only run the linux_setup role for Debian or RedHat OS families in this case.
Looping through Roles
Using the loop keyword, we can also iterate over a list and include a role multiple times. An example is as follows:
- hosts: all
tasks:
- name: Setup multiple users
include_role:
name: user_setup
vars:
username: "{{ item }}"
user_group: "db_users"
loop:
- mysql
- mongodb
- sqlite
This creates the mysql, mongodb, and sqlite users using the user_setup role.
Conclusion
You learned how to use the include_role directive to offer flexibility and reusability, simplifying the design of Ansible playbooks.