---
# System prepended metadata

title: Ansible Roles

---


### What is an Ansible role?
:::info
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 in roles, you can easily reuse them and share them with other users.
:::
:arrow_right: *https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html*


### Working with Ansible Roles

### Ansible Galaxy Commands
````yaml=
Check local roles:
ansible-galaxy role list

Create a local role:
ansible-galaxy init <role-name>

Explore Ansible Galaxy:
galaxy.ansible.com

Go to (one of) default location for ansible roles:
cd ~/.ansible
mkdir roles && cd roles

Install a role from Ansible Galaxy:
ansible-galaxy install <authorname.rolename>

Validate the role installation:
ansible-galaxy role list
````
### Use a role to work with Nginx

#### Install the role
```yaml=
ansible-galaxy install geerlingguy.nginx
```

#### Write a playbook to call the role

````yaml=
## vi role-play.yaml

--- ## Playbook to call nginx role
- hosts: nodes
  become: yes
  tasks:
    - name: install and manage nginx
      include_role:
        name: geerlingguy.nginx
````
:arrow_right: *Please note that you need to have the role installed on the controller already before you can use it in a playbook*

#### Run the Playbook
````yaml=
ansible-playbook role-play.yaml
````
#### Validate the changes
````yaml=
curl localhost
or 
elinks http://localhost
or 
which nginx
or
sudo systemctl status nginx
````

### Configure a LAMP server using Ansible roles
```yaml=
L -> Linux
A -> Apache
M -> MySQL
P -> PHP

Step1: Install relevant roles:

ansible-galaxy install geerlingguy.php
ansible-galaxy install geerlingguy.mysql
ansible-galaxy install geerlingguy.apache

Step 2: Write a playbook to call the roles:

--- ## Playbook to call nginx role
- hosts: webservers
  become: yes
  tasks:
    - name: install LAMP
      include_role:
          - geerlingguy.php
          - geerlingguy.mysql
          - geerlingguy.apache
          
Step 3: Run the Playbook:

ansible-playbook lamp.yaml

Step 4: Validate:
which php / apache2 / mysql
or
systemctl status apache2
or
curl localhost
```






### References:
:::info
- https://docs.ansible.com/ansible/latest/reference_appendices/general_precedence.html
- https://galaxy.ansible.com/home
- https://galaxy.ansible.com/geerlingguy/nginx
- 
:::
