Interview › Infrastructure as Code (Terraform, Ansible)
What is the difference between Ansible roles and collections?
Infrastructure as Code (Terraform, Ansible) · Advanced level
Answer
A role is a reusable automation structure for tasks, handlers, defaults, and templates. A collection is a distribution package that can include roles, modules, plugins, playbooks, and documentation under a namespace. Collections are how Ansible content is shared and versioned at ecosystem scale.
Technical explanation
Collections use fully qualified collection names such as ansible.builtin.copy or community.mysql.mysql_db.
Roles can live inside collections, but roles can also be standalone.
Pin collection versions in requirements.yml for reproducible automation.
Prefer idempotent modules over shell so repeated runs are safe and change reporting is meaningful.
Separate reusable role logic from inventory-specific variables so the same automation works across environments.
Run lint, syntax checks, check mode where useful, and staged rollouts before production-wide changes.
Hands-on example
1. Package reusable Ansible content for: What is the difference between Ansible roles and collections?
2. Create a role structure:
roles/web/
defaults/main.yml
tasks/main.yml
handlers/main.yml
templates/nginx.conf.j2
files/
meta/main.yml
3. Call the role from a playbook:
- name: Configure web tier
hosts: web
roles:
- role: web
vars:
web_listen_port: 80804. If distributing modules/plugins/roles together, package them as a collection and pin it in requirements.yml.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is delegate_to, and when would you use it?
- What is a Jinja2 template, and how is it used in Ansible?
- What is max_fail_percentage, and how does it protect a rollout?
- How do you run an Ansible playbook in check (dry-run) mode?
- What is the serial keyword, and how does it enable rolling updates?
- What is the difference between state: present and state: latest, and the risk of latest?
- What is a loop in Ansible, and how do you iterate over a list?
- How do you handle host-specific differences across a mixed fleet?