Roles are a good way to organize ansible playbooks. Roles allow group the tasks, handlers, files, templates and variable definitions. Following an example of roles definition and its tree.
--- - name: Example of role.yml - hosts: all pre_tasks: # to run before all role/tasks - debug: msg: 'Starting ...' roles: - role1 - role2 post_tasks: # to run after all role/tasks - debug: msg: '... Finished.'
Following the tree with its explanation.
$ tree roles/ ├── defaults # default values of role variables │ └── main.yml ├── files # static files which can be used as reference ├── handlers # handler definitions │ └── main.yml ├── meta # contains information about the role, for example the author and license and role dependencies │ └── main.yml ├── tasks # tasks definitions │ └── main.yml ├── templates # templates definitions ( e.g using jinja ) │ └── apache.j2 ├── tests # playbooks to test the role │ └── inventory │ └── test.yml └── vars # role's variable values └── main.yml
Following an example with a role which is calling another by the dependency configuration.
--- # It is the file roles/myvhost/meta/main.yml in the above struture dependencies: - { role: myfirewall, firewall_variable: value_over }
Then, when the playbook which is in the same directory of the roles dir described above be executed calling the myvhost role the myfirewall role will be executed first. Following the playbook.yml which has this example.
--- - name: Example of playbook with roles hosts: all pre_tasks: - debug: msg: 'Starting' # here will be executed firt the roles/myfirewall/tasks/main.yml # then will be called the roles/myvhost/tasks/main.yml roles: - myvhost post_tasks: - debug: msg: 'Finished'
NOTES:
The following command can be used to create the local structure for roles.
ansible-galaxy init --offline -p roles <newrole-name
>
The default path to install roles will be the path of Ansible. The roles_path attribute in the ansible.cfg file as follows can be used to define the roles dir in the project.
[defaults] inventory = inventory remote_user = root roles_path = roles [privilege_escalation] become = true
Following some Ansible documentation references