# Role Structure — Ansible: Automate Servers with Playbooks

Source: https://www.geekswithgeeks.com/en/ansible/role-structure

> Create a role skeleton and know what each directory is for.

## A standard layout

A **role** is a directory with a fixed structure that Ansible knows how to load: `tasks/` (the work, starting from `main.yml`), `handlers/`, `templates/`, `files/`, `defaults/` (low-priority variables users can override), `vars/` (higher-priority internal variables), `meta/` (dependencies and metadata) and `tests/`. Playbooks then become short: they list which roles apply to which hosts. `ansible-galaxy role init` creates the skeleton.

## Package your automation

Roles bundle tasks, templates, defaults and handlers into a reusable unit you can share across projects.

![Three steps: structure, share, apply.](assets/figures/ansible/section-5-map.svg) — Figure 5.1 — Structure, share and apply.

## Scaffold a role, run

I ran this: Ansible created the role and these directories.

```bash
ansible-galaxy role init demo_role
ls demo_role
```

Output:

```
- Role demo_role was created successfully
defaults
files
handlers
meta
README.md
tasks
templates
tests
vars
```

## Using the role in a playbook

The playbook stays short; the role holds the details. (Illustrative.)

```yaml
---
- name: Web tier
  hosts: web
  become: true
  roles:
    - role: nginx
      vars:
        nginx_port: 8080
    - role: app_deploy
```

**Quiz:** Which role directory holds the low-priority variables users can override?

- [ ] handlers/
- [ ] files/
- [x] defaults/
- [ ] tests/

*Answer:* defaults/. defaults/main.yml sets the weakest variables, designed to be overridden.
