Ansible: Automate Everything from First Playbook to Production · Roles and Ansible Galaxy
Roles: Reusable Automation Packages
Organise tasks, handlers, templates, variables and files into a role that any playbook can include — the standard unit of reuse in Ansible.
What you'll build
A base role that sets up a server with standard packages, a deploy user, SSH hardening and an NTP configuration — reusable across every host in your inventory.
The idea
A role is a directory with a fixed layout. Ansible loads each subdirectory automatically:
roles/base/
├── tasks/main.yml # entry point — task list
├── handlers/main.yml # handlers (restart, reload)
├── templates/ # Jinja2 .j2 files
├── files/ # static files (copied as-is)
├── vars/main.yml # high-precedence internal variables
├── defaults/main.yml # low-precedence defaults (consumers override these)
└── meta/main.yml # role metadata: author, dependencies, min_ansible_version
Why roles over flat playbooks?
- Reuse — include the same role in ten playbooks without copying tasks.
- Encapsulation — the role owns its templates, handlers and defaults together.
- Testing — test one role in isolation with Molecule.
- Sharing — push to Galaxy or a private Git repository.
Scaffold a new role:
ansible-galaxy role init roles/base
include_role vs import_role: import_role is static — Ansible resolves it at parse time, so conditionals on the import affect every task. include_role is dynamic — resolved at runtime, so you can loop over it or put it inside a conditional block.
Role dependencies in meta/main.yml let you declare that your webserver role needs the base role to run first:
dependencies:
- role: base
vars:
base_packages:
- curl
- unzip
The code
mkdir -p role-demo/roles/base/{tasks,handlers,templates,defaults}
cat > role-demo/roles/base/defaults/main.yml <<'EOF'
base_packages:
- curl
- wget
- vim
- htop
base_deploy_user: deploy
base_timezone: UTC
base_ntp_servers:
- 0.pool.ntp.org
- 1.pool.ntp.org
EOF
cat > role-demo/roles/base/tasks/main.yml <<'EOF'
- name: Install base packages
ansible.builtin.debug:
msg: "Would install: {{ base_packages | join(', ') }}"
- name: Create deploy user
ansible.builtin.debug:
msg: "Would create user: {{ base_deploy_user }}"
- name: Set timezone
ansible.builtin.debug:
msg: "Would set timezone to {{ base_timezone }}"
- name: Deploy NTP config
ansible.builtin.template:
src: ntp.conf.j2
dest: /tmp/ntp.conf
mode: "0644"
notify: restart ntp
- name: Show NTP config
ansible.builtin.command: cat /tmp/ntp.conf
register: ntp_out
changed_when: false
- name: Display NTP config
ansible.builtin.debug:
msg: "{{ ntp_out.stdout }}"
EOF
cat > role-demo/roles/base/handlers/main.yml <<'EOF'
- name: restart ntp
ansible.builtin.debug:
msg: "Would restart NTP service"
EOF
cat > role-demo/roles/base/templates/ntp.conf.j2 <<'EOF'
# Managed by Ansible — do not edit
driftfile /var/lib/ntp/ntp.drift
{% for server in base_ntp_servers %}
server {{ server }} iburst
{% endfor %}
EOF
cat > role-demo/inventory.ini <<'EOF'
[webservers]
localhost ansible_connection=local
EOF
cat > role-demo/site.yml <<'EOF'
- name: Configure webservers
hosts: webservers
gather_facts: false
roles:
- role: base
vars:
base_timezone: America/New_York
EOF
cd role-demo
ansible-playbook -i inventory.ini site.yml 2>/dev/null
Output
Run this on your computer — see “Get Started” for setup.
The playbook overrode base_timezone but kept the default packages and NTP servers. The handler fired because the template task reported changed.
Common mistakes
Putting all tasks in one giant tasks/main.yml — split into focused files and use include_tasks from main.yml:
# tasks/main.yml
- include_tasks: packages.yml
- include_tasks: users.yml
- include_tasks: ntp.yml
Using import_role inside a loop — static imports cannot be looped. Use include_role when you need dynamic behavior like loops or conditional includes.
Hardcoding values in vars/main.yml that consumers need to change — anything the consumer should override belongs in defaults/main.yml. Reserve vars/ for internal constants.
Key points
- A role's directory layout (
tasks/,handlers/,templates/,defaults/,vars/,files/,meta/) is loaded automatically. defaults/main.ymlholds values consumers can override;vars/main.ymlholds internal constants.import_roleis static (parse-time);include_roleis dynamic (runtime) — use dynamic for loops and conditionals.ansible-galaxy role initscaffolds the directory structure for a new role.
Practice questions
What is the difference between `defaults/main.yml` and `vars/main.yml` in a role?
Answer
defaults/ holds low-precedence values that consumers are expected to override. vars/ holds high-precedence internal constants that should not be changed by consumers.
When should you use `include_role` instead of `import_role`?
Answer
Use include_role when you need dynamic behavior — looping over roles, conditional includes, or when the role name comes from a variable. Use import_role for static, unconditional includes.
How do you declare that one role depends on another?
Answer
Add the dependency in meta/main.yml under the dependencies key. Ansible runs dependencies before the role's own tasks.
Open in the app to mark lessons complete, take notes and track your progress.