Creating Reusable Roles
Creating Reusable Roles
Role Development Workflow
Planning Phase
- Define role purpose
- Identify dependencies
- Plan directory structure
- Determine variables
Implementation Steps
- Initialize role structure
ansible-galaxy init role_name
- Define metadata
- Create tasks
- Set default variables
- Add handlers if needed
Role Development Best Practices
Modularity
- Single responsibility principle
- Clear dependencies
- Minimal coupling
- Maximum cohesion
Naming Conventions
# Good Examples
roles/
webserver/ # Clear purpose
database_mysql/ # Specific implementation
security_base/ # Functional area
# Bad Examples
roles/
role1/ # Unclear purpose
stuff/ # Too generic
misc/ # Not descriptive
Variable Management
# defaults/main.yml
---
app_port: 8080
app_user: "webapp"
app_group: ""
app_config_template: "app.conf.j2"
app_config_path: "/etc/app/config.conf"
app_features:
logging: true
monitoring: false
backups: true
Testing and Validation
Test Structure
# tests/inventory
[local]
localhost ansible_connection=local
# tests/test.yml
---
- hosts: local
roles:
- role: your_role_name
vars:
app_port: 9000
Testing Methods
- Syntax Check
ansible-playbook --syntax-check tests/test.yml
- Dry Run
ansible-playbook -C tests/test.yml
- Full Test
ansible-playbook tests/test.yml
Molecule Testing
# molecule/default/molecule.yml
---
dependency:
name: galaxy
driver:
name: docker
platforms:
- name: instance
image: ubuntu:latest
pre_build_image: true
provisioner:
name: ansible
verifier:
name: ansible
Documentation Standards
README Structure
# Role Name
Brief description of the role's purpose
## Requirements
List prerequisites and dependencies
## Role Variables
Document all variables and their defaults
## Dependencies
List required roles
## Example Playbook
Show usage examples
## License
Specify the license
## Author Information
Provide contact details
Variable Documentation
# defaults/main.yml
---
# Port number for the application
# Default: 8080
app_port: 8080
# User to run the application
# Default: webapp
app_user: webapp
# Feature flags for optional components
# Default: see below
app_features:
logging: true # Enable application logging
monitoring: false # Enable monitoring integration
backups: true # Enable automated backups
Version Control
Git Structure
role_name/
.git/
.gitignore
molecule/
tasks/
templates/
tests/
README.md
meta/main.yml
.gitignore Example
*.retry
*.pyc
__pycache__/
.molecule/
.cache/
Practical Exercise
Creating a Web Server Role
- Initialize role structure
- Implement basic tasks
- Add configuration templates
- Write tests
- Document the role
Role Testing Process
- Syntax validation
- Local testing
- Integration testing
- Documentation review
Key Takeaways
- Plan before implementing
- Test thoroughly
- Document comprehensively
- Follow best practices