In our previous post we have learnt how to write a playbook. Most of the complex projects need more playbooks. It is often more confusing and hard to maintain many playbooks, also there would be lot of code redundancy. To reuse most of the code, maintain easily ansible provides a way and it is though roles.
There are lot of advantages of using roles in ansible. We will learn them as we go on.
So what is a role in a more simpler way?
Precisely a role is a systematic breaking of code to reuse the functionality and place them in predefined directories to work. The predefined directories are :
- tasks – contains the main list of tasks to be executed by the role.
- handlers – contains handlers, which may be used by this role or even anywhere outside this role.
- defaults – default variables for the role.
- vars – other variables for the role.
- files – contains files which can be deployed via this role.
- templates – contains templates which can be deployed via this role.
- meta – defines some meta data for this role. See below for more details
Once a role is created we use this role (i.e we execute the role in playbook) and get our job done.
Let us see how we convert play to/create a role in ansible. We will create a role to install Docker and spin up a Jenkins server.
- First create a directory called roles in project root folder.
- In roles directory run the following command
ansible-galaxy init <rolename> .
- Here we took Jenkins as role name so the command will be
ansible-galaxy init Jenkins
- The output will be as below.
The directory will be as below :
Roles is all about breaking the functionality into small block/tasks so that they could be reused.
Once the directory is created, inside tasks we create files which have the tasks to be performed. Here in our case the task is to install docker and spin up the Jenkins container. The file main.yml will be called by default so we need to reference/include/import other tasks files to be used if any or write the tasks in main.yml itself. Since our scenario is simple i have written the tasks in main.yml
---
# tasks file for Jenkins
- name: install docker
apt:
name: docker
state: present
register: aptop
- name: pull docker image and spin up
docker_image:
name: jenkins/jenkins
source: pull
- name: spin up container
docker_container:
name: ansiblejenkins
image: jenkins/jenkins
ports:
- "8080:8080"
Once the tasks are written successfully we need to call the roles in main playbook and run the playbook. (hosts info will be in playbook not in roles)
---
#hosts can be anything on which you need the role to run
- name: calling jenkins role
hosts: remotehost
roles:
- Jenkins
This is a very simple way how you can get started with roles. Let us learn about reusing the blocks i.e include,import and more about vars etc in the coming posts.
Please feel free to comment and share.