Ansible: Roles
Ansible's roles allow grouping the content, which can be reused and easily share with other users. The role consists of vars, files, tasks, and other artifacts in a standard directory structure which have these subdirectories.
- Tasks
- Handlers
- Library
- Default
- Vars
- Files
- Templates
- Meta
We can use roles in the playbook or task with the help of Include and Import. To know more about Import/Include, you can check here
- At Playbook level with the
roles
- At task level with
include_roles
- At task level with
import_roles
Playbook Roles at playbook level are imported statically and executes the playbook in this order
- Pre tasks
- Roles listed in the playbook
- Tasks define in the playbook and any handler triggered by the tasks
- Post tasks define after the role
---
- hosts: webservers
roles:
- aws
Task with Include
---
- hosts: all
tasks:
- name: Use a dynamic roles
include_roles:
name: role_name
Task with Import
---
- hosts: all
tasks:
- name: Use a static roles
import_role:
name: role_name
Passing parameter to the roles
---
- hosts: all
roles:
- { role: aws, message: "ec2" }
- { role: aws, message: "s3" }
Conditionally adding roles
---
- hosts: all
tasks:
- name: Include the some_role role
include_role:
name: some_role
when: "ansible_facts['os_family'] == 'Ubuntu'"
Ansible's roles are really helpful to group the similar content and use in the different playbook and give the feasibility to the user to share with other which saves a lot of work. It's worth using them and shares your roles in the community to help others.
Cheers!