[Ansible] – Understanding roles

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 ...'
    - 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.

Screen Shot 2018-10-31 at 17.04.01

# It is the file roles/myvhost/meta/main.yml in the above struture
  - { 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

    - debug:
        msg: 'Starting' 
  # here will be executed firt the roles/myfirewall/tasks/main.yml 
  # then will be called the roles/myvhost/tasks/main.yml 
    - myvhost
    - debug:
        msg: 'Finished'


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.

inventory = inventory
remote_user = root
roles_path = roles

become = true

Following some Ansible documentation references


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s