Roles is the reusable unit of Ansible. You may think of it as a function.
It:
Roles expect files to be in certain directory names.
site.yml
webservers.yml
fooservers.yml
roles/
common/
main.yml
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
main.yml
tasks/
defaults/
meta/
where:
Example: Galaxy Role
Role variable section
Ansible will search for roles in the following way:
The role path is where ansible will search for a role.
By default: ~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
The role path may be overwritten via:
ansible-galaxy install --roles-path . geerlingguy.apache
{{ role_path }}
ansible-galaxy init rolename
ansible-galaxy collection init
molecule init role -r my-new-role
Via a Ansible - Playbook (Doc)
---
- hosts: webservers
roles:
- common
- webservers
vars:
dir: '/opt/b'
app_port: 5001
- '/path/to/my/roles/common'
vars:
dir: '/opt/a'
app_port: 5000
tasks:
...
---
- hosts: webservers
roles:
- {role: 'common', tags: 'common' }
- {role: 'webservers', tags: 'webservers' }
- {role: 'mysql', tags: 'mysql'}
- {role: 'apache', tags: 'apache'}
ansible-playbook webserver.yml --tags "apache"
With ansible
ansible -m include_role -a 'name=rolname' myhosts
Example with the ansible directory as subdirectory:
ansible -i ansible/hosts-local.ini --playbook-dir=ansible -m include_role -a 'name=rolname' hostPattern
Role dependencies are always executed before the role that includes them, and may be recursive.
See Ansible - Molecule (Role Test)
from Ansible galaxy (installing-roles or galaxy Installing content)
ansible-galaxy install namespace.role_name,version
# or
ansible-galaxy install git+url,(commit|branch)
# or an installation in the working directory
ansible-galaxy install --roles-path . namespace.role_name
Example:
ansible-galaxy install geerlingguy.apache,v1.0.0
# git
ansible-galaxy install git+https://github.com/geerlingguy/ansible-role-apache.git,0b7cd353c0250e87a26e0499e59e7fd265cc2f25
If the role path is not specified via the roles-path option at the command line:
All installed roles can be listed with the following command:
ansible-galaxy list