Create Reusable Ansible Roles
Intermediate15 minTrending
Structure automation into reusable roles with tasks, handlers, templates, defaults, and metadata for sharing across projects.
Prerequisites
- -Ansible installed
- -Basic playbook knowledge
Steps
1
Initialize a role skeleton
Creates the standard role directory structure with tasks, handlers, defaults, vars, templates, files, and meta.
$ ansible-galaxy role init roles/nginx
2
Define default variables
Defaults have the lowest precedence and can be overridden by users of the role.
$ cat > roles/nginx/defaults/main.yml << 'EOF'
---
nginx_port: 80
nginx_worker_processes: auto
nginx_server_name: localhost
EOF
3
Write the main tasks
Tasks use handlers for service restarts and templates for dynamic configuration.
$ cat > roles/nginx/tasks/main.yml << 'EOF'
---
- name: Install nginx
apt:
name: nginx
state: present
notify: restart nginx
- name: Deploy nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: restart nginx
- name: Ensure nginx is running
service:
name: nginx
state: started
enabled: true
EOF
4
Create a handler
Handlers run only when notified by a task that made a change, avoiding unnecessary restarts.
$ cat > roles/nginx/handlers/main.yml << 'EOF'
---
- name: restart nginx
service:
name: nginx
state: restarted
EOF
5
Use the role in a playbook
Imports the role and overrides default variables at the play level.
$ cat > site.yml << 'EOF'
---
- name: Deploy web servers
hosts: webservers
become: true
roles:
- role: nginx
nginx_port: 8080
nginx_server_name: app.example.com
EOF
Full Script
FAQ
Discussion
Loading comments...