4. Roles

  • It is a concept that deals with ideas rather than events. It is basically another level of abstraction used to organize playbooks

  • They provide a skeleton for an independent and reusable collection of variables, tasks, templates, files and modules which can be automatically loaded into the playbook


Creation

ansible galaxy

it is a website that lets ansible users share their roles and modules

usage

ansible-galaxy init roleName

Directory Structure

default

contain the default variables that are going to be used for by this role

files

contains files that can be deployed by this role. It contains files that need to be sent to the hosts while configuring the role.

handlers

contains handlers which may be used by this role or outside this particular role

meta

defines metadata for this role. Basically, it contains files that establish role dependencies.

tasks

contains main list of tasks that are to be executed by the role. It contains the main.yml file for that particular role.

templates

contains files which can be modified and added to the host being provisioned Jinja2(template language) is used to achieve the modifications.

tests

it is used to integrate testing with Ansible Playbooks.

vars

it consists of other variables that are going to be used by the role. these variables can be defined in your playbook, but it's a good habit to define them in this section.


Sample Role NodeJS

Create a role named nodejs inside /etc/ansible/roles directory and then create a file named main.yml inside /etc/ansible/roles/nodejs directory.

- name: Node.Js - Get script
  get_url:
    url: "http://deb.nodesource.com/setup_6.x"
    dest: "{{ var_node }}/nodejs.sh"

- name: Node.Js - Set exec perm to script
  file:
    path: "{{ var_node }}/nodejs.sh"
    mode: "u+x"

- name: Node.Js - Exec install script
  shell: "http://deb.nodesource.com/setup_6.x"

- name: Node.Js - Remove install script
  file:
    path: "{{ var_node }}/nodejs.sh"
    state: absent

- name: Node.Js - Install Node.js
  apt: name={{ item }} state=present update_cache=yes
  with_items:
    - build-essential
    - nodejs

- name: Install NPM
  apt:
    name: npm
    state: present

- name: Node.js | Install bower and gulp globally
  npm: name={{ item }} state=present global=yes
  with_items:
    - bower
    - gulp

Sample Playbook

This playbook will be created in /etc/ansible directory and will refer the role nodejs

- hosts: all
  become: true
  vars:
    # needed for node installation
	  ansible_become_pass: aziz
	  var_node: /tmp
  roles:
    - nodejs

Last updated