Explain Ansible roles structure, Galaxy, and Collections. How do you organize a large-scale Ansible codebase?
Quick Answer
Roles package tasks/handlers/templates/vars into reusable units. Galaxy is the public registry. Collections bundle roles+modules+plugins into distributable packages. Organize with a mono-repo of roles with molecule testing.
Detailed Answer
Role Structure
`` roles/nginx/ ├── defaults/main.yml # Default variables (lowest priority) ├── vars/main.yml # Role variables (high priority) ├── tasks/main.yml # Task list ├── handlers/main.yml # Handlers (notify triggers) ├── templates/ # Jinja2 templates ├── files/ # Static files ├── meta/main.yml # Dependencies, Galaxy metadata └── molecule/ # Test scenarios ``
Collections (Ansible 2.10+)
Collections are the modern packaging format that bundles roles, modules, plugins, and documentation together. Namespaced: community.general, amazon.aws, kubernetes.core.
Galaxy: Public registry for sharing roles and collections. Private Galaxy alternatives: Ansible Automation Hub (Red Hat), Pulp, or simple Git repos.
Large-Scale Organization
- Mono-repo with all roles, playbooks, and inventories - requirements.yml pins external collection/role versions - Molecule tests for every role (Docker-based testing) - Group vars organized by environment (dev/staging/prod) - Dynamic inventory for cloud resources (AWS, GCP, Azure plugins) - Ansible Vault for encrypted secrets
Code Example
# requirements.yml - pin external dependencies
collections:
- name: amazon.aws
version: ">=6.0.0,<7.0.0"
- name: kubernetes.core
version: ">=3.0.0"
roles:
- name: geerlingguy.docker
version: 6.1.0
# Install dependencies
ansible-galaxy install -r requirements.yml
# Molecule test for nginx role
# molecule/default/molecule.yml
driver:
name: docker
platforms:
- name: ubuntu
image: ubuntu:22.04
pre_build_image: true
verifier:
name: ansible
# molecule/default/converge.yml
- hosts: all
roles:
- role: nginx
nginx_worker_processes: auto
# Run tests
cd roles/nginx && molecule test
# Playbook using roles
- hosts: webservers
roles:
- role: common
- role: nginx
vars:
nginx_vhosts:
- server_name: api.example.com
proxy_pass: http://localhost:8080Interview Tip
Mention molecule testing — it's the standard for role testing and shows you write testable infrastructure code. The Collections architecture is the modern approach; roles alone are legacy.