Ansible uses the concept of roles to better allow modular code and avoid repeating yourself.
A role is simply a folder structure that Ansible knows where to load vars files, tasks and handlers from. An example might look something like this:
apache/
├── defaults
│ └── main.yml
├── files
│ ├── mod-pagespeed-stable_current_i386.deb
│ ├── mod-pagespeed-stable_current_i386.rpm
│ ├── mod-pagespeed-stable_current_amd64.deb
| └── mod-pagespeed-stable_current_x86_64.rpm
├── tasks
│ ├── debian.yml
│ ├── main.yml
│ └── redhat.yml
├── templates
│ ├── httpd.conf.j2
│ └── sites-available
│ └── virthualhost.conf.j2
└── vars
├── debian
└── redhat
You can then use the role with a basic playbook that just looks like this:
- hosts: webservers
roles:
- apache
When you run Ansible against this playbook it will target all the hosts in the webservers
group and run the apache
role defined above against it, automatically loading any default variables for the role and running all the tasks included in tasks/main.yml
. Ansible also knows to look for certain types of files in role friendly locations:
If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play
If roles/x/handlers/main.yml exists, handlers listed therein will be added to the play
If roles/x/vars/main.yml exists, variables listed therein will be added to the play
If roles/x/meta/main.yml exists, any role dependencies listed therein will be added to the list of roles (1.3 and later)
Any copy, script, template or include tasks (in the role) can reference files in roles/x/{files,templates,tasks}/ (dir depends on task) without having to path them relatively or absolutely