patternbashansibleTip
Ansible roles structure reusable configuration as composable units
Viewed 0 times
ansible rolesgalaxydefaultshandlerstemplatesrole dependenciesansible-galaxy initrequirements.yml
Problem
Copying task blocks between playbooks leads to drift and makes it hard to apply the same configuration to new host groups. Large playbooks become monolithic and hard to test in isolation.
Solution
Package related tasks, handlers, templates, files, and defaults into a role. Use
Role structure:
ansible-galaxy init to generate the standard directory layout. Consume roles from Ansible Galaxy or a private repository.# Generate a new role skeleton
ansible-galaxy init roles/nginxRole structure:
roles/nginx/
tasks/
main.yml # Main task list
handlers/
main.yml # Handlers (e.g., restart nginx)
templates/
nginx.conf.j2 # Jinja2 templates
files/
index.html # Static files to copy
defaults/
main.yml # Default variable values (lowest precedence)
vars/
main.yml # Role variables (higher precedence than defaults)
meta/
main.yml # Role metadata and dependenciesroles/nginx/defaults/main.yml:nginx_port: 80
nginx_worker_processes: autoroles/nginx/tasks/main.yml:---
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
- name: Configure nginx
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginxWhy
Roles encapsulate a unit of functionality with a well-defined interface (defaults). They can be versioned, shared via Ansible Galaxy, and composed together in a playbook to configure a complete server.
Gotchas
- Variables in
defaults/main.ymlhave the lowest precedence — they are easily overridden by inventory or playbook vars - Variables in
vars/main.ymlhave higher precedence and are harder to override — use them for role-internal constants - Role dependencies in
meta/main.ymlare applied before the role's own tasks - Tag roles in
requirements.ymland install withansible-galaxy install -r requirements.yml
Context
Building reusable Ansible configuration components for server setup and application deployment
Revisions (0)
No revisions yet.