supraj.dev

Interview questions & answers

Ansible

Playbooks, roles, automation, and configuration management.

  • 13 questions
  • 3 easy
  • 6 medium
  • 4 hard

13 questions

Question 1Easy

What is Ansible and how does it differ from Terraform?

#
Show answer

Ansible is a configuration management and automation tool that uses SSH (no agent needed) and YAML playbooks. It is procedural and focuses on configuring existing systems. Terraform is declarative and focuses on provisioning infrastructure. Ansible is idempotent, agentless, and primarily used for OS config, app deployment, and orchestration. Terraform is used for cloud resource provisioning. They complement each other — Terraform provisions VMs, Ansible configures them.

Question 2Easy

What is an Ansible Playbook?

#
Show answer

A Playbook is a YAML file containing one or more plays. Each play maps a group of hosts to a set of tasks executed in order. Example: - name: Configure web server; hosts: webservers; become: yes; tasks: - name: Install nginx; apt: name: nginx state: present. Playbooks are the entry point for all automation. They can include variables, handlers, templates, roles, and conditionals.

Question 3Medium

What is an Ansible Role and how does its directory structure work?

#
Show answer

A Role is a reusable, self-contained unit of automation with a standard directory structure: roles/role_name/{tasks, handlers, templates, files, vars, defaults, meta, library, lookup_plugins, module_utils}. Each directory contains a main.yml that Ansible loads automatically. Roles are referenced in playbooks: - hosts: webservers; roles: [common, nginx]. Roles can have dependencies (meta/main.yml). Pre-built roles are shared via Ansible Galaxy.

Question 4Medium

What are Ansible modules and what types exist?

#
Show answer

Modules are discrete units of code that Ansible runs on targets. Types: (1) System — package, service, user, mount, firewalld. (2) Commands — command, shell, raw, script. (3) Files — copy, template, file, fetch, lineinfile. (4) Database — mysql_db, postgresql_db, mongo_db. (5) Cloud — ec2, gce, azure_rm, s3. (6) Kubernetes — k8s, helm. (7) Network — ios, junos, nxos. Modules are idempotent — they check current state before making changes. ansible-doc -l lists all available modules.

Question 5Medium

How does Ansible Vault work for secrets management?

#
Show answer

Ansible Vault encrypts sensitive data (variables, files) at rest. Commands: ansible-vault create secret.yml, ansible-vault encrypt vars.yml, ansible-vault view secret.yml. Run playbooks with --ask-vault-pass or --vault-password-file. Encrypted variables are decrypted at runtime. Multiple vault passwords are supported (labeled vault IDs): ansible-playbook --vault-id prod@prompt site.yml. Vault encrypts the entire file content (AES-256). For per-value encryption, use lookup plugins or integrate with HashiCorp Vault.

Question 6Hard

How does Ansible variable precedence work (the full order from lowest to highest)?

#
Show answer

Variable precedence (lowest to highest): (1) role defaults, (2) inventory file vars, (3) inventory group_vars, (4) inventory host_vars, (5) playbook group_vars/host_vars, (6) set_facts, (7) play vars, (8) play vars_prompt, (9) play vars_files, (10) role vars (from roles/x/vars/main.yml), (11) block vars, (12) task vars, (13) include_vars results, (14) registered vars, (15) extra vars (-e "key=value"). Extra vars always win. Use ansible-inventory --vars to debug variable resolution. Variables in group_vars/all/ apply to all hosts.

Question 7Hard

How do you test Ansible playbooks and what tools are available?

#
Show answer

Tools: (1) ansible-playbook --check — dry-run (reports changes without making them). (2) --diff — shows what would change. (3) Molecule — testing framework for Ansible roles: creates instances (Docker, Vagrant, AWS), runs converge, verifies with verify (using testinfra), and destroys. (4) ansible-lint — checks playbooks for best practices and anti-patterns. (5) Testinfra — Python test framework for verifying system state after Ansible runs: def test_nginx_running(host): assert host.service("nginx").is_running. (6) Ansible-specific CI in GitHub Actions with molecule action.

Question 8Medium

What are Ansible handlers and when are they triggered?

#
Show answer

Handlers are tasks that only run when notified by other tasks. Defined under handlers:, triggered via notify: handler_name. They run once at the end of the play, even if notified multiple times. Common use: restarting a service after config change: - name: Restart nginx; service: name: nginx state: restarted; listen: restart nginx. Use meta: flush_handlers to run handlers immediately (e.g., before a task that depends on the handler's effect). Handlers can also be triggered by listen (multiple handlers with the same listen topic).

Question 9Hard

How do you implement zero-downtime deployments with Ansible?

#
Show answer

Strategy: (1) Use serial to control batch size: - hosts: app_servers; serial: 1 (one at a time). (2) Pre-check: run health check before removing old version. (3) Deploy new version with a symlink swap: deploy_dir: /app/current (symlink to /app/releases/v2). (4) Use delegate_to with a load balancer to remove/add nodes from the LB pool: - name: Remove from LB; delegate_to: localhost; haproxy: state: disabled; host: "{{ inventory_hostname }}". (5) Post-check: wait for new app to be healthy: uri: url: http://localhost:8080/health; status_code: 200. (6) Rollback on failure: symlink back to previous release. The serial: 1 ensures only one server is down at a time.

Question 10EasyIdempotence

What does idempotent mean in Ansible, and how do you prove a role is idempotent?

#

Every run of a role reports changes, so nobody trusts the change summary.

Show answer

Idempotent means running the role again on a configured host changes nothing: the second run reports changed=0. Most modules check state before acting, but command and shell always report changed unless you add creates, removes or a changed_when condition.

Prove it automatically: Molecule's idempotence step converges a test instance twice and fails if the second run reports changes. Fix offenders by replacing shell commands with proper modules or adding accurate change detection.

Trade-offs

Accurate change reporting takes extra conditions, but without it you cannot tell a real change from noise.

Common mistake

Setting changed_when: false everywhere to make the report look clean.

Follow-up

How would you make a task that runs a database migration report changes correctly?

Question 11MediumSafety

How do you preview a risky Ansible change on production hosts?

#

A template change touches nginx configuration on 300 servers.

Show answer

Run the playbook with --check --diff: check mode reports what would change without changing it, and diff shows the file differences. Not every module supports check mode, and tasks that depend on earlier tasks' results may behave differently, so read the output critically.

Then apply to a small group first with --limit or a canary group, verify the service, and roll out to the rest in batches.

Trade-offs

Check mode is a preview, not a guarantee; some changes only show up when tasks really run.

Common mistake

Treating a clean check run as proof the real run will succeed.

Follow-up

How would you mark a task that must always run, even in check mode?

Question 12MediumTooling

Playbooks work on your laptop but fail in CI. How do execution environments help?

#

CI has a different Ansible version, missing collections and a different Python library.

Show answer

An execution environment is a container image with ansible-core, the collections you need, and their Python and system dependencies. You define it in a file and build it with ansible-builder, then run playbooks inside it with ansible-navigator, locally and in CI.

Everyone uses the same versions, and upgrades become a reviewed image change. Pin collection versions in requirements.yml and tag images by version.

Trade-offs

Images add a build step and registry to maintain, but they remove a lot of "works on my machine" debugging.

Common mistake

Installing collections at run time in CI from whatever version is latest.

Follow-up

How would you test a collection upgrade before rolling out the new image?

Question 13HardRolling updates

A patch run across 500 hosts took a service down. How would you make it safe?

#

The playbook patched and rebooted every web server at once.

Show answer

Use serial to process hosts in batches, for example serial: ["1", "10%", "25%"]. Set max_fail_percentage so the play stops if too many hosts in a batch fail.

In pre_tasks, remove each host from the load balancer with a task delegated to the LB or its API; in post_tasks, wait for the service with a health check using until and retries before adding it back. Use any_errors_fatal for steps where one failure should stop everything.

Trade-offs

Smaller batches are safer but take longer; size them to the capacity you can lose.

Common mistake

Rebooting without waiting for the host and service to come back before the next batch.

Follow-up

How would you resume a rolling update that stopped at batch four?