Ansible Interview Questions and Answers
Last updated 2026-11-19
Ansible interviews focus on whether you think declaratively and idempotently. Anyone can write a playbook that works once; the questions that matter are why command and shell tasks are discouraged, how variable precedence resolves, how handlers behave and how you keep secrets out of Git. This page has 15 worked questions with YAML you can run against a local VM or container.
Examples use ansible-core with fully qualified collection names such as ansible.builtin.copy, the recommended style in current versions. For provisioning cloud resources, compare with the Terraform questions, and for the wider workflow see the DevOps questions.
| Model | Agentless, push-based, YAML playbooks over SSH (or WinRM for Windows) |
|---|---|
| Building blocks | Inventory, modules, tasks, plays, playbooks, roles, collections |
| Key property | Idempotency: running twice makes no further changes |
A playbook to read line by line
This play installs and configures Nginx on hosts in the web group. Be ready to explain become, the package module's idempotency, the template's validate parameter, and why the restart is a handler that fires only when the configuration actually changed.
---
- name: Configure web servers
hosts: web
become: true
vars:
http_port: 8080
tasks:
- name: Install nginx
ansible.builtin.package:
name: nginx
state: present
- name: Deploy site config
ansible.builtin.template:
src: site.conf.j2
dest: /etc/nginx/conf.d/site.conf
owner: root
mode: "0644"
validate: nginx -t -c /etc/nginx/nginx.conf
notify: Reload nginx
- name: Ensure nginx is running and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloadedAnsible Interview Questions and Answers: questions with worked answers
1 How does Ansible work, and why is it called agentless?
easyThe control node runs ansible or ansible-playbook, reads the inventory, connects to each managed node over SSH (WinRM or PSRP for Windows), copies small module scripts to a temporary directory, executes them with the node's Python interpreter, collects JSON results and removes the files. No daemon or agent needs installing or maintaining on managed hosts, only SSH access and Python for most modules. That keeps bootstrap simple, but it is push-based and sequential per task across hosts, so large fleets use forks, strategies such as free, pipelining and tools like AWX or Automation Controller for scheduling.
2 What is idempotency in Ansible? Why is the shell module discouraged?
easyAn idempotent task checks current state and acts only if it differs from the desired state, reporting changed or ok accordingly. The package module installs a package only if absent; the user, file and service modules behave the same. The shell and command modules run arbitrary commands and always report changed unless you add logic, so repeated runs may have side effects. When you must use them, make them safe with creates, removes or changed_when and failed_when conditions, or check mode support. Prefer a purpose-built module first.
yaml- name: Initialise the database once ansible.builtin.command: /opt/app/bin/init-db args: creates: /var/lib/app/.initialised - name: Check version without reporting a change ansible.builtin.command: /opt/app/bin/app --version register: ver changed_when: false3 Explain inventory: static, dynamic, groups and group_vars.
mediumAn inventory lists the hosts Ansible manages, organised into groups. A static inventory is an INI or YAML file. A dynamic inventory is generated by a plugin or script that queries a source such as AWS EC2, Azure or a CMDB, so new instances appear automatically, often grouped by tags. Variables attach at several levels: group_vars/web.yml applies to a group, host_vars/web1.yml to one host. The special group all contains every host and children groups nest. Patterns such as web:&prod or web:!staging select intersections and exclusions when you limit with --limit.
yamlall: children: web: hosts: web1.example.com: web2.example.com: vars: http_port: 8080 db: hosts: db1.example.com: ansible_user: ubuntubashansible-inventory -i inventory.yml --graph ansible web -i inventory.yml -m ansible.builtin.ping ansible-playbook -i inventory.yml site.yml --limit web1.example.com --check --diff4 What are handlers and when do they run?
mediumA handler is a task that runs only when notified by another task that reported changed, and runs once at the end of the play even if notified many times. They are meant for actions such as reloading a service after a config change. If a task fails before the end of the play, handlers do not run by default, so a notified restart may be skipped; use force_handlers or meta: flush_handlers to run them earlier, for instance when a later task depends on the service being reloaded. Handlers are matched by name, or by the listen keyword for topics.
5 What is a role and how is it structured?
easyA role is a standard directory layout that packages tasks, handlers, defaults, vars, templates, files and metadata for reuse. tasks/main.yml is the entry point, defaults/main.yml holds low-precedence variables meant to be overridden, vars/main.yml holds higher-precedence internal values, templates contains Jinja2 files, and meta/main.yml lists dependencies. Roles are shared through Ansible Galaxy or Git, and collections now bundle roles, modules and plugins. Create the skeleton with ansible-galaxy role init. Keep defaults documented and prefix role variables with the role name to avoid collisions.
6 What is the variable precedence order, in practice?
mediumThere are 22 levels in the documentation, but the practical ordering from lowest to highest is: role defaults, inventory group_vars, inventory host_vars, play vars, role vars, task vars, registered and set_fact facts, and extra vars passed with -e, which always win. The advice that follows is to put overridable settings in role defaults, per-environment values in group_vars, and use -e only for one-off overrides. Debug confusing values with the debug module or ansible-inventory --host name.
7 How do you protect secrets in Ansible with Vault?
mediumansible-vault encrypts a whole file or a single value using AES-256, so secrets can live in Git safely. Typical practice is to keep an encrypted vars file next to a plain one that references it, supply the password through a password file or secrets manager rather than typing it, and use vault IDs to separate environments. The decrypted values are available to playbooks at runtime, and tasks handling them should set no_log: true so they do not appear in output. For larger setups, a lookup plugin that reads from HashiCorp Vault or a cloud secrets manager avoids storing secrets in the repository at all.
bashansible-vault create group_vars/prod/vault.yml ansible-vault edit group_vars/prod/vault.yml ansible-vault encrypt_string 's3cr3t' --name 'db_password' ansible-playbook site.yml --vault-password-file ~/.vault_pass8 How do loops, conditionals and register work together?
mediumloop repeats a task over a list, exposing item; when applies a Jinja2 conditional per host or per iteration; register stores a task's result in a variable for later use. Combine them to react to the state of a system. Remember that when expressions are written without double braces. Use failed_when to define your own failure condition, and ignore_errors only when a failure is genuinely acceptable. For reading data from tasks use the facts gathered at the start, available as ansible_facts, for example the distribution family.
yaml- name: Install packages per OS family ansible.builtin.package: name: "{{ item }}" state: present loop: "{{ pkgs[ansible_facts['os_family']] }}" - name: Check disk usage ansible.builtin.command: df --output=pcent / register: df changed_when: false - name: Fail when disk is nearly full ansible.builtin.fail: msg: "Root filesystem is {{ df.stdout_lines[1] | trim }} full" when: (df.stdout_lines[1] | trim | replace('%','') | int) > 909 How do Jinja2 templates differ from the copy module?
easycopy transfers a file unchanged, while template renders a Jinja2 file on the control node with variables, facts, loops and conditionals, then writes the result. Use it for configuration such as nginx.conf, where values vary per host or environment. Template files by convention end in .j2. Add validate to test the rendered file before replacing the live one, and set ansible_managed comments carefully so teammates know not to edit by hand. Filters such as default, join and to_nice_json transform data inside templates.
text# {{ ansible_managed }} server { listen {{ http_port | default(80) }}; server_name {{ inventory_hostname }}; {% for upstream in app_servers %} # upstream: {{ upstream }} {% endfor %} }10 What are facts, and how can you speed up or disable fact gathering?
mediumFacts are system details such as OS family, IP addresses, memory and mounts, gathered by the setup module at the start of each play and stored under ansible_facts. They allow conditional logic per platform. Gathering costs time on large inventories, so set gather_facts: false when a play does not use facts, gather only a subset with gather_subset, or enable fact caching in a Redis or JSON file cache so repeated runs reuse them. You can also gather custom facts from files in /etc/ansible/facts.d.
11 How do you run Ansible safely on a large fleet: serial, check mode and diff?
hardUse serial to roll changes through batches, for example serial: 2 or a percentage, with max_fail_percentage so a bad change stops after a small number of hosts instead of the whole fleet. Before a risky run, use --check for a dry run and --diff to see file changes; remember that not every module supports check mode and tasks depending on earlier changes may report inaccurately. Add health-check tasks after each batch, take hosts out of the load balancer with delegate_to during updates, and limit with --limit when testing a single host.
yaml- hosts: web serial: "25%" max_fail_percentage: 10 tasks: - name: Deploy release ansible.builtin.unarchive: src: "app-{{ version }}.tar.gz" dest: /opt/app - name: Wait for the health endpoint ansible.builtin.uri: url: "http://localhost:{{ http_port }}/health" status_code: 200 register: r retries: 10 delay: 3 until: r.status == 20012 What is the difference between include_tasks and import_tasks?
hardimport_tasks is static: Ansible parses and inlines the tasks when the playbook is loaded, so tags and conditions apply to each imported task and errors surface early, but it cannot use loops or variables that are only known at runtime. include_tasks is dynamic: it is evaluated when execution reaches it, so it can be looped or conditioned on runtime variables, but tags apply only to the include itself and --list-tasks will not show its contents. Use import for fixed structure and include for runtime-dependent logic. The same split exists for roles with import_role and include_role.
13 How do you debug a failing playbook?
mediumRaise verbosity with -v up to -vvvv to see connection and module details, use the debug module to print variables, and use --step to confirm each task, --start-at-task to resume, and --syntax-check or ansible-lint to catch mistakes early. Check connectivity with the ping module, privilege escalation settings and the Python interpreter path. Run the failing task against a single host with --limit. For module output, register the result and print it. Writing tasks with clear names helps because the failing task name appears in the output.
bashansible-playbook site.yml --syntax-check ansible-lint site.yml ansible-playbook site.yml -vvv --limit web1.example.com --start-at-task "Deploy site config"14 Ansible versus Puppet and Chef: how do they compare?
easyPuppet and Chef traditionally use an agent on each node that pulls its catalogue from a server on a schedule and continuously converges state, with their own DSLs (Puppet language, Ruby for Chef). Ansible is agentless and push-based with YAML, which is easier to start with and good for orchestration across hosts, while pull-based agents are stronger at continuous enforcement of drift without a human triggering a run. Ansible can approximate that with scheduled runs through AWX or ansible-pull. Immutable images and containers have reduced the role of all three for application hosts.
Frequently asked questions
Do I need Python to use Ansible?
Ansible itself is written in Python and most modules need Python on managed hosts, but you can write playbooks without coding in it. Python helps when writing custom modules, filters or dynamic inventory scripts.
What is the difference between a playbook and a role?
A playbook maps hosts to tasks and roles in a run. A role is a reusable, structured bundle of tasks, templates and defaults that a playbook calls, so the same logic can serve many playbooks.
What are Ansible collections?
Collections are the distribution format for modules, plugins, roles and playbooks, versioned and installed with ansible-galaxy collection install. Most modules now live in collections such as amazon.aws, community.general and kubernetes.core, not in the core package.
Is Ansible still relevant with Kubernetes and Terraform?
Yes, for configuring VMs and network devices, patching, bootstrapping hosts and orchestrating multi-step operations. It complements Terraform for provisioning and sits alongside Kubernetes rather than replacing it.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- API Testing and Postman Interview Questions
- Automation Testing Interview Questions and Answers
- AWS Interview Questions and Answers
- Azure Interview Questions and Answers
- Backend Developer Interview Questions and Answers
- Business Analyst Interview Questions and Answers
- Cloud Engineer Interview Questions and Answers
- Computer Vision Interview Questions and Answers
- Cybersecurity Interview Questions and Answers
- Data Analyst Interview Questions and Answers
- Data Engineer Interview Questions and Answers
- Data Scientist Interview Questions and Answers