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: 8080

4. If distributing modules/plugins/roles together, package them as a collection and pin it in requirements.yml.

Preparing for an interview?

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

← All Infrastructure as Code (Terraform, Ansible) questions