There are a few different ways to invoke one or more roles in a playbook.
- roles (this article)
- import_playbook
- import_role
- include_role
- include_tasks
- import_tasks
With roles, you will need to create the roles directories, subdirectories, and files. You can:
- Use the ansible-galaxy init command to create the roles files and directories
- Use the ansible-galaxy install command to create the roles files and directories
- Use the git clone command to create the roles files and directories
- Manually create the roles files and directories
Here is an example of the directory structure used with roles.
├── /usr/local
│ ├── main.yml
│ ├── roles
│ │ ├── foo
│ │ ├── ├── defaults
│ │ ├── ├── ├── main.yml
│ │ ├── ├── files
│ │ ├── ├── ├── main.yml
│ │ ├── ├── handlers
│ │ ├── ├── ├── main.yml
│ │ ├── ├── meta
│ │ ├── ├── ├── main.yml
│ │ ├── ├── tasks
│ │ ├── ├── ├── main.yml
│ │ ├── ├── templates
│ │ ├── ├── ├── main.yml
│ │ ├── ├── vars
│ │ ├── ├── ├── main.yml
Where should the "roles" files and directories reside?
Let's say your playbook wants to use the "foo" role.
---
- hosts: all
roles:
- foo
...
Or like this.
---
- hosts: all
roles:
- role: foo
...
Ansible will search the following directories for the "foo" role:
- The directory that contains your playbook (e.g. /home/john.doe/)
- /etc/ansible/roles/
Let's say you define some other roles_path in ansible.cfg.
roles_path = /usr/local/ansible/roles
Or using the ANSIBLE_ROLES_PATH variable.
export ANSIBLE_ROLES_PATH=/usr/local/ansible/roles
Now Ansible will search the following directories for the "foo" role:
- The directory that contains your playbook (e.g. /home/john.doe/)
- /usr/local/ansible/roles
It is noteworthy that if you have a role that resides in some other directory, say /usr/local/testing/roles, the role can be used by including the absolute path to the role in your playbook.
---
- hosts: all
roles:
- /usr/local/testing/roles/foo
...
It is also possible to pull in roles from a Git repository.
Variables
Each role can have it's own unique set of variables. Refer to Role Variables.
pre_tasks and post_tasks
When using the roles module, tasks will be performed in this order:
- pre_tasks
- If the pre_tasks include the notify module, the handlers will be run.
- If the role contains any dependencies, the dependencies will be run.
- tasks
- If the tasks include the notify module, the handlers will be run.
- post_tasks
- If the post_tasks include the notify module, the handlers will be run.
Perform tasks on the control node
Refer to run tasks on the control node if you want to run this module on your control node.
Did you find this article helpful?
If so, consider buying me a coffee over at