Home Interview Top Ansible Interview Questions for DevOps Engineers (2025)
Intermediate 3 min · July 13, 2026

Top Ansible Interview Questions for DevOps Engineers (2025)

Master Ansible with our comprehensive interview guide covering playbooks, roles, modules, idempotency, and real-world debugging.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of Linux command line and SSH
  • Familiarity with YAML syntax
  • Knowledge of basic networking and server management
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Ansible is an agentless automation tool using SSH.
  • Playbooks are YAML files defining automation tasks.
  • Idempotency ensures repeated runs produce the same result.
  • Roles organize playbooks into reusable components.
  • Key modules: command, shell, copy, file, yum, apt, service, template.
✦ Definition~90s read
What is Ansible Interview Questions?

Ansible is an open-source automation tool that uses SSH to manage configurations, deploy applications, and orchestrate tasks without requiring agents on managed nodes.

Think of Ansible as a remote control for your servers.
Plain-English First

Think of Ansible as a remote control for your servers. Instead of logging into each server manually to run commands, you write a recipe (playbook) that tells all your servers what to do. Ansible follows the recipe exactly, and if you run it again, it only changes things that are out of sync—like a smart to-do list that checks off tasks already done.

Ansible has become a cornerstone of modern DevOps, enabling infrastructure as code (IaC) with simplicity and power. In interviews, you'll be expected to demonstrate not just syntax knowledge but a deep understanding of Ansible's architecture, best practices, and troubleshooting. This guide covers the most common Ansible interview questions, from basic concepts to advanced topics like custom modules and dynamic inventories. We'll explore real-world scenarios, including a production incident that highlights the importance of idempotency and error handling. Whether you're preparing for a DevOps engineer role or a platform engineer position, mastering these questions will give you the confidence to ace your interview. Let's dive into the world of Ansible and equip you with the knowledge to succeed.

1. What is Ansible and how does it work?

Ansible is an open-source automation tool that automates configuration management, application deployment, and task orchestration. It is agentless, meaning it does not require any software installed on managed nodes. Instead, it uses SSH (or WinRM for Windows) to connect and execute tasks. Ansible follows a push-based model: the control node pushes modules to managed nodes, executes them, and removes them after completion. Playbooks are YAML files that define the desired state of systems. Ansible uses a declarative approach—you describe what the end state should be, and Ansible ensures that state is achieved. Key components include the inventory (list of hosts), modules (units of work), and roles (reusable collections of tasks).

basic_ping.ymlYAML
1
2
3
4
5
6
---
- name: Test connectivity
  hosts: all
  tasks:
    - name: Ping all hosts
      ping:
Output
SUCCESS => {
"changed": false,
"ping": "pong"
}
🔥Agentless Advantage
📊 Production Insight
In large environments, SSH multiplexing can speed up connections. Use 'ssh_args' in ansible.cfg.
🎯 Key Takeaway
Ansible uses SSH to push modules; no agent required on managed nodes.

2. Explain idempotency in Ansible.

Idempotency means that running a playbook multiple times produces the same result without unintended side effects. Ansible modules are designed to be idempotent: they check the current state before making changes. For example, the 'file' module creates a file only if it doesn't exist; the 'yum' module installs a package only if it's not already installed. This ensures that playbooks can be run repeatedly without causing drift. However, not all modules are inherently idempotent—the 'command' and 'shell' modules run every time unless you use 'creates' or 'when' conditions. Best practice is to use idempotent modules whenever possible and avoid 'command' unless necessary.

idempotent_example.ymlYAML
1
2
3
4
5
6
7
8
9
---
- name: Ensure package is installed
  yum:
    name: httpd
    state: present

- name: Non-idempotent command
  command: echo "Hello" > /tmp/hello.txt
  creates: /tmp/hello.txt
Output
PLAY RECAP: ok=2 changed=1
💡Idempotency Check
📊 Production Insight
Always test idempotency in staging; non-idempotent tasks can cause configuration drift over time.
🎯 Key Takeaway
Idempotency ensures consistent state; prefer modules that check state before making changes.

3. What are Ansible roles and how do you structure them?

Roles are a way to organize playbooks into reusable components. Each role has a standard directory structure: tasks, handlers, templates, files, vars, defaults, meta, and tests. This structure promotes modularity and reusability. For example, a 'webserver' role might contain tasks to install Apache, templates for virtual hosts, and handlers to restart the service. Roles can be shared via Ansible Galaxy. To use a role, you include it in a playbook using the 'roles' keyword. Best practices include using 'defaults' for default variables and 'vars' for overrides, and keeping roles focused on a single function.

role_structure.txtTEXT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
roles/
  common/
    tasks/
      main.yml
    handlers/
      main.yml
    templates/
      ntp.conf.j2
    files/
      motd
    vars/
      main.yml
    defaults/
      main.yml
    meta/
      main.yml
    tests/
      inventory
      test.yml
🔥Role Discovery
📊 Production Insight
Use Ansible Galaxy to download community roles, but always review them for security.
🎯 Key Takeaway
Roles organize tasks, handlers, and variables into reusable units with a standard directory layout.

4. How do you handle variables in Ansible?

Variables in Ansible can be defined in multiple places with a specific precedence order (from lowest to highest): role defaults, inventory vars, inventory group_vars, inventory host_vars, playbook vars, playbook vars_prompt, playbook vars_files, role vars (defined in role/vars), block vars, task vars, extra vars (passed via command line). The highest precedence wins. Variables can be used in playbooks using Jinja2 templating ({{ variable }}). Best practices include using descriptive names, avoiding hardcoding, and leveraging 'group_vars' and 'host_vars' for environment-specific settings. Use 'debug' module to print variable values during development.

variable_example.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
---
- hosts: all
  vars:
    package: httpd
  tasks:
    - name: Install {{ package }}
      yum:
        name: "{{ package }}"
        state: present
    - name: Show variable
      debug:
        var: package
Output
ok: [server1] => {
"package": "httpd"
}
⚠ Variable Precedence
📊 Production Insight
Avoid storing secrets in plain text; use Ansible Vault to encrypt sensitive variables.
🎯 Key Takeaway
Variables follow a strict precedence; use group_vars for environment defaults and extra vars for overrides.

5. Explain Ansible modules and give examples of commonly used ones.

Modules are the units of work in Ansible. They are executed on the managed node and can be written in Python, PowerShell, or other languages. Common modules include: 'command' (runs a command), 'shell' (runs a command via shell), 'copy' (copies files), 'file' (manages file attributes), 'yum'/'apt' (package management), 'service' (manages services), 'template' (Jinja2 templating), 'user' (user management), 'lineinfile' (ensure line in file), and 'debug' (print messages). Each module has parameters and returns JSON output. Use 'ansible-doc' to view module documentation.

module_example.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
---
- name: Install and start nginx
  hosts: webservers
  tasks:
    - name: Install nginx
      yum:
        name: nginx
        state: present
    - name: Start nginx
      service:
        name: nginx
        state: started
        enabled: yes
    - name: Copy config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: restart nginx
  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted
Output
PLAY RECAP: ok=3 changed=2
💡Module Documentation
📊 Production Insight
Custom modules can be written in Python and placed in the 'library' directory.
🎯 Key Takeaway
Modules are the building blocks; use idempotent modules like 'yum' and 'service' over 'command'.

6. What is Ansible Galaxy and how do you use it?

Ansible Galaxy is a hub for finding, sharing, and managing Ansible roles. You can download roles from Galaxy using the 'ansible-galaxy' command. For example, 'ansible-galaxy install geerlingguy.apache' installs a role. You can also create roles with 'ansible-galaxy init role_name'. Galaxy allows you to manage dependencies via a 'requirements.yml' file. Best practices include specifying version numbers in requirements and reviewing roles before use. Galaxy also supports namespaces and collections (Ansible 2.9+), which bundle multiple roles and modules.

requirements.ymlYAML
1
2
3
4
5
6
7
8
9
---
roles:
  - name: geerlingguy.apache
    version: 3.1.0
  - name: geerlingguy.nginx
    version: 2.7.0
collections:
  - name: community.general
    version: 4.0.0
🔥Galaxy vs Collections
📊 Production Insight
Pin role versions to avoid breaking changes from upstream updates.
🎯 Key Takeaway
Galaxy provides reusable roles; use 'requirements.yml' to manage dependencies.

7. How do you manage secrets in Ansible?

Ansible Vault encrypts sensitive data like passwords, keys, and API tokens. You can encrypt entire files or individual variables. Use 'ansible-vault create' to create a new encrypted file, 'ansible-vault encrypt' to encrypt an existing file, and 'ansible-vault decrypt' to decrypt. When running a playbook, provide the vault password via '--ask-vault-pass' or a password file. Vault IDs allow multiple passwords. Best practices include never committing unencrypted secrets to version control, using vault for sensitive variables, and integrating with external secret managers like HashiCorp Vault.

vault_example.shBASH
1
2
3
4
5
6
7
8
9
10
11
# Create encrypted file
ansible-vault create secrets.yml

# Encrypt existing file
ansible-vault encrypt vars/passwords.yml

# Run playbook with vault
ansible-playbook playbook.yml --ask-vault-pass

# Use vault ID
ansible-playbook playbook.yml --vault-id prod@vault-pass.txt
⚠ Vault Password Security
📊 Production Insight
For dynamic secrets, consider using the 'hashi_vault' lookup plugin.
🎯 Key Takeaway
Ansible Vault encrypts sensitive data; use it for passwords and keys.

8. What are handlers in Ansible?

Handlers are special tasks that run only when notified by another task. They are typically used for restarting services after configuration changes. Handlers are defined in the 'handlers' section of a playbook or role, and tasks notify them using the 'notify' keyword. Handlers run at the end of the play, in the order they are defined, and only once even if notified multiple times. This prevents unnecessary restarts. You can also force handlers to run with 'meta: flush_handlers'.

handler_example.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
- name: Configure web server
  hosts: webservers
  tasks:
    - name: Update config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: restart nginx
  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted
Output
RUNNING HANDLER [restart nginx]...
💡Handler Execution
📊 Production Insight
Use 'listen' to group multiple notifications to the same handler.
🎯 Key Takeaway
Handlers run on notification, typically for service restarts, and execute once at play end.

9. How do you test Ansible playbooks?

Testing Ansible playbooks involves syntax checks, dry runs, and integration tests. Use 'ansible-playbook --syntax-check' to validate YAML syntax. '--check' mode performs a dry run without making changes. '--diff' shows changes. For unit testing, use 'ansible-playbook' with '--step' to confirm each task. For integration testing, tools like Molecule provide a framework for testing roles in containers or VMs. Molecule supports drivers like Docker, Vagrant, and AWS. It runs converge, verify, and destroy phases. Use 'ansible-lint' to enforce best practices.

molecule_test.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
- name: Converge
  hosts: all
  roles:
    - role: my_role

- name: Verify
  hosts: all
  tasks:
    - name: Check service is running
      service:
        name: nginx
        state: started
      check_mode: no
🔥Molecule
📊 Production Insight
Run 'ansible-lint' in CI to catch common issues early.
🎯 Key Takeaway
Use syntax checks, dry runs, and Molecule for comprehensive testing.

10. What is dynamic inventory and how do you implement it?

Dynamic inventory allows Ansible to fetch host information from external sources like cloud providers (AWS, GCP, Azure), CMDB, or custom scripts. Instead of a static file, you use a script or plugin that returns JSON. Ansible provides built-in inventory plugins for major clouds. For example, the 'aws_ec2' plugin uses boto3 to list EC2 instances. You can also write custom scripts in any language that output JSON with the required structure. Dynamic inventory enables auto-scaling and reduces manual maintenance.

aws_ec2.ymlYAML
1
2
3
4
5
6
7
8
9
10
plugin: aws_ec2
regions:
  - us-east-1
filters:
  tag:Environment: production
hostnames:
  - dns-name
keyed_groups:
  - key: tags.Name
    prefix: tag_Name_
💡Inventory Scripts
📊 Production Insight
Cache dynamic inventory results to improve performance; use 'cache' plugin.
🎯 Key Takeaway
Dynamic inventory fetches hosts from external sources; use plugins for cloud providers.
● Production incidentPOST-MORTEMseverity: high

The Case of the Disappearing Cron Jobs

Symptom
Users reported missing scheduled backups and maintenance tasks.
Assumption
The developer assumed the cron module would only add new jobs, not replace existing ones.
Root cause
The 'cron' module with 'state=present' and no 'name' parameter overwrote the entire crontab file.
Fix
Added unique 'name' to each cron job and used 'backup=yes' to preserve previous crontab.
Key lesson
  • Always use unique 'name' for cron jobs to avoid overwriting.
  • Enable 'backup' option for critical file modifications.
  • Test playbooks in a staging environment before production.
  • Use 'check_mode' to preview changes before applying.
  • Implement idempotent tasks to prevent unintended side effects.
Production debug guideSymptom to Action4 entries
Symptom · 01
Playbook hangs or times out
Fix
Check SSH connectivity and increase timeout with 'timeout' parameter.
Symptom · 02
Task fails with 'unreachable'
Fix
Verify inventory hostnames and SSH keys; use 'ping' module to test.
Symptom · 03
Idempotency not working
Fix
Review task logic; use 'changed_when' and 'failed_when' to control status.
Symptom · 04
Variable not resolving
Fix
Check variable precedence; use 'debug' module to print variable values.
★ Quick Debug Cheat SheetCommon Ansible issues and immediate actions.
SSH connection refused
Immediate action
Check SSH service and firewall
Commands
ansible all -m ping -i inventory
ssh -vvv user@host
Fix now
Ensure SSH port is open and key is authorized.
YAML syntax error+
Immediate action
Validate YAML
Commands
ansible-playbook playbook.yml --syntax-check
python -c "import yaml; yaml.safe_load(open('playbook.yml'))"
Fix now
Correct indentation and quotes.
Module not found+
Immediate action
Check module name and path
Commands
ansible-doc -l | grep module_name
ansible-playbook playbook.yml -M /path/to/modules
Fix now
Install missing module or use full path.
FeatureAnsiblePuppetChef
ArchitectureAgentless (SSH)Agent-basedAgent-based
LanguageYAMLDSL (Puppet)Ruby DSL
IdempotencyBuilt-inBuilt-inBuilt-in
Learning CurveLowMediumHigh
Push/PullPushPullPull
⚙ Quick Reference
10 commands from this guide
FileCommand / CodePurpose
basic_ping.yml- name: Test connectivity1. What is Ansible and how does it work?
idempotent_example.yml- name: Ensure package is installed2. Explain idempotency in Ansible.
role_structure.txtroles/3. What are Ansible roles and how do you structure them?
variable_example.yml- hosts: all4. How do you handle variables in Ansible?
module_example.yml- name: Install and start nginx5. Explain Ansible modules and give examples of commonly use
requirements.ymlroles:6. What is Ansible Galaxy and how do you use it?
vault_example.shansible-vault create secrets.yml7. How do you manage secrets in Ansible?
handler_example.yml- name: Configure web server8. What are handlers in Ansible?
molecule_test.yml- name: Converge9. How do you test Ansible playbooks?
aws_ec2.ymlplugin: aws_ec210. What is dynamic inventory and how do you implement it?

Key takeaways

1
Ansible is agentless and uses SSH for automation; idempotency is key to reliable playbooks.
2
Roles and Ansible Galaxy promote modularity and reuse; always pin versions.
3
Use Ansible Vault for secrets, dynamic inventory for cloud environments, and Molecule for testing.
4
Understand variable precedence and use 'defaults' for overridable values.
5
Debug with '--check', '--diff', and 'debug' module; handle errors with 'block' and 'rescue'.

Common mistakes to avoid

5 patterns
×

Using 'command' module instead of idempotent modules

×

Not using 'name' parameter in cron module

×

Hardcoding variables in playbooks

×

Forgetting to use '--check' before running playbooks

×

Not using Ansible Vault for secrets

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What is the difference between 'command' and 'shell' modules?
Q02SENIOR
How do you implement a rolling update with Ansible?
Q03SENIOR
Explain the difference between 'vars' and 'defaults' in a role.
Q04SENIOR
How do you create a custom module in Ansible?
Q05SENIOR
What is 'delegate_to' and when would you use it?
Q01 of 05JUNIOR

What is the difference between 'command' and 'shell' modules?

ANSWER
'command' runs a command without shell processing (no pipes, redirects, etc.), while 'shell' runs through the shell and supports shell features. Use 'command' for simple commands to avoid shell injection risks.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the difference between Ansible and Terraform?
02
How do you handle errors in Ansible playbooks?
03
Can Ansible manage Windows servers?
04
What is the purpose of 'ansible.cfg'?
05
How do you optimize Ansible performance?
N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Written from production experience, not tutorials.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's DevOps Interview. Mark it forged?

3 min read · try the examples if you haven't

Previous
Linux and SRE Interview Questions
9 / 9 · DevOps Interview