Ansible Playbook Roles

Ansible Playbook Roles





In this article, we will read about ansible-playbook roles. what is this and how does it work.

Roles let you automatically load related vars, files, tasks, handlers, and other Ansible artifacts based on a known file structure. After you group your content into roles, you can easily reuse them and share them with other users.

Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules.

In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of the playbook allows you to logically break the playbook into reusable components.

An Ansible role has a defined directory structure with eight main standard directories. You must include at least one of these directories in each role. You can omit any directories the role does not use.

For example:

# playbooks
site.yml
webservers.yml
fooservers.yml
roles/
    common/
    tasks/
    handlers/
    library/
    files/
    templates/
    vars/
    defaults/
    meta/
    webservers/
    tasks/
    defaults/
    meta/


tasks/main.yml - the main list of tasks that the role executes.

handlers/main.yml - handlers, which may be used within or outside this role.

library/my_module.py - modules, which may be used within this role.

defaults/main.yml - default variables for the role. These variables have the lowest priority of any variables available and can be easily overridden by any other variable, including inventory variables.

vars/main.yml - other variables for the role.

files/main.yml - files that the role deploys.

templates/main.yml - templates that the role deploys.

meta/main.yml - metadata for the role, including role dependencies.

Process:-

[user@ip]# mkdir -p playbook/roles/webserver/tasks

[user@ip]# tree                      (It will show tree hierarchy of playbook roles)

[user@ip]# cd playbook/

[user@ip playbook]# touch roles/webserver/tasks/main.yml

[user@ip playbook]# touch master.yml

[user@ip playbook]# vi roles/webserver/tasks/main.yml

inside main.yml type

-name: install apache
yum: pkg=httpd state=latest


and the save it and exit

[user@ip playbook]# vi master.yml

--- #Playbook Roles
- host: all
  user: ansible
 become: yes
 connection: ssh
 roles:
    - webserver


and then save it and exit

[user@ip playbook]# ansible-playbook master.yml



Share:

0 comments

Please leave your comments...... Thanks