Prev Next

DevOps / Ansible Interview questions

1. What is Ansible? 2. What are the key features of Ansible? 3. What is a playbook in Ansible? 4. Define an inventory file in Ansible? 5. What is a module in Ansible? 6. What are Ansible facts? 7. Describe roles in Ansible? 8. What are the types of variables in Ansible? 9. List the components of an Ansible role directory? 10. How do you use handlers in Ansible? 11. What is Ansible Vault? 12. Explain the purpose of tags in Ansible playbooks? 13. What is ansible.cfg? 14. How do you apply become for privilege escalation in Ansible? 15. What is Ansible Galaxy? 16. Why doesn't Ansible require agents on managed nodes? 17. How does Ansible ensure idempotency in playbook runs? 18. What is the difference between include and import in Ansible? 19. When should you use loops instead of duplicating tasks? 20. What happens when a task fails in an Ansible playbook? 21. How is variable precedence resolved in Ansible? 22. Why should you avoid hardcoding secrets in playbooks? 23. What is the difference between Ansible and Chef/Puppet? 24. How does Ansible handle privilege escalation with become? 25. When would you choose dynamic inventory over static inventory? 26. How can you optimize playbook execution speed? 27. What is the difference between copy and template modules? 28. Why do we use handlers instead of regular tasks for restarts? 29. How does Ansible's Jinja2 templating work in playbooks? 30. What is the difference between roles and collections? 31. When should you use blocks with rescue in Ansible? 32. How is check mode implemented in Ansible? 33. Why doesn't Ansible require a central server by default? 34. What is the difference between ansible-playbook and ansible ad-hoc commands? 35. How do you troubleshoot a failing Ansible task? 36. Explain the internal working of Ansible's execution model? 37. Explain the execution flow of an Ansible playbook run? 38. Explain the lifecycle of a task in an Ansible play? 39. How does Ansible guarantee idempotent module behavior internally? 40. What happens internally when Ansible gathers facts? 41. How can you optimize a large-scale Ansible deployment for performance? 42. Which is better and why: linear or free strategy for a large inventory? 43. How does forking improve execution speed in Ansible? 44. Why is idempotency critical to Ansible's module design? 45. How do you troubleshoot slow fact gathering in Ansible? 46. Explain the internal working of Ansible's variable precedence resolution? 47. What happens when a handler is notified multiple times in a play? 48. How does Ansible implement fact caching internally? 49. Explain the execution flow of a rolling update using serial? 50. How can you optimize role design to avoid duplicate work at scale?

1. What is Ansible?

Ansible is an open-source, agentless automation tool used for configuration management, application deployment, and orchestration. It connects to managed nodes over standard SSH (or WinRM for Windows) and pushes changes out, rather than requiring a persistent agent installed on every target machi...

Read full answer

2. What are the key features of Ansible?

Agentless - connects over SSH/WinRM, no software to install on managed nodes. Declarative YAML playbooks - describe desired state, not step-by-step commands. Idempotent modules - re-running a playbook only changes what's actually out of state. Reusable roles and collections - packaged, shareable ...

Read full answer

3. What is a playbook in Ansible?

A playbook is a YAML file that defines one or more plays , each of which maps a group of hosts to an ordered list of tasks to run against them. It's the primary unit of automation in Ansible, describing what should happen and where. --- - name: Configure web servers hosts: webservers become: true...

Read full answer

4. Define an inventory file in Ansible?

An inventory file lists the managed nodes Ansible can operate on, organized into groups so playbooks can target them by name. It can be as simple as a static INI or YAML file, or generated dynamically by querying a cloud provider or CMDB. # INI-style static inventory [webservers] web1.example.com...

Read full answer

5. What is a module in Ansible?

A module is a self-contained, reusable unit of code that performs one specific piece of work, such as installing a package, copying a file, or creating a cloud resource. Tasks in a playbook are really just calls to a module with a set of arguments. - name: Ensure a config file is present ansible....

Read full answer

6. What are Ansible facts?

Facts are pieces of information Ansible automatically discovers about a managed host at the start of a play, such as its IP addresses, OS distribution, kernel version, mounted filesystems, and available memory. They're gathered by the built-in setup module, which runs implicitly unless gather_fac...

Read full answer

7. Describe roles in Ansible?

A role is a standardized way of packaging a set of tasks, handlers, variables, templates, and files around a single purpose, like "configure nginx" or "install a database," so that logic can be reused across multiple playbooks and projects. roles/ nginx/ tasks/main.yml handlers/main.yml templates...

Read full answer

8. What are the types of variables in Ansible?

Ansible pulls variables from many possible sources, each with a different scope and precedence. Source Typical use Role defaults ( defaults/main.yml ) Lowest-precedence, overridable fallback values. Inventory / group_vars / host_vars Environment- or host-specific settings. Play vars / vars_files ...

Read full answer

9. List the components of an Ansible role directory?

A standard role follows a fixed layout that Ansible auto-discovers, with each subdirectory holding a specific kind of content: tasks/main.yml - the main list of tasks the role performs. handlers/main.yml - handlers the role's tasks can notify. defaults/main.yml - lowest-precedence default variabl...

Read full answer

10. How do you use handlers in Ansible?

A handler is a task that only runs when explicitly triggered by another task's notify directive, and typically only when that task actually reports a change. Handlers are the standard way to express "restart this service, but only if its configuration actually changed." tasks: - name: Update ngin...

Read full answer

11. What is Ansible Vault?

Ansible Vault is a built-in feature for encrypting sensitive content, like passwords, API keys, or entire variable files, so secrets can be safely committed to version control alongside the rest of a playbook. ansible-vault encrypt secrets.yml ansible-vault view secrets.yml ansible-playbook site....

Read full answer

12. Explain the purpose of tags in Ansible playbooks?

Tags let you label individual tasks, roles, or blocks so you can selectively run or skip parts of a playbook at execution time, instead of always running everything from top to bottom. tasks: - name: Install packages ansible.builtin.package: name: nginx tags: [install] - name: Deploy configuratio...

Read full answer

13. What is ansible.cfg?

ansible.cfg is Ansible's main configuration file, controlling default behavior like which inventory file to use, connection settings, privilege escalation defaults, and plugin paths, so these don't need to be repeated as command-line flags on every run. [defaults] inventory = ./inventory/producti...

Read full answer

14. How do you apply become for privilege escalation in Ansible?

become tells Ansible to execute a task (or an entire play) as a different user, typically root, using a privilege escalation method like sudo , rather than requiring the SSH connection itself to log in as that user. - name: Install a system package hosts: webservers become: true become_user: root...

Read full answer

15. What is Ansible Galaxy?

Ansible Galaxy is both a public hub for sharing reusable roles and collections, and the ansible-galaxy command-line tool for installing them into a local project. ansible-galaxy install geerlingguy.nginx ansible-galaxy collection install community.docker # requirements.yml roles: - name: geerling...

Read full answer

16. Why doesn't Ansible require agents on managed nodes?

Ansible was deliberately designed to avoid the operational overhead that agent-based tools carry: installing, upgrading, and keeping a background service running and secure on every single managed node, which itself becomes something that needs monitoring and patching over time. Instead, Ansible ...

Read full answer

17. How does Ansible ensure idempotency in playbook runs?

Idempotency in Ansible comes from module design, not from the playbook or engine automatically detecting "nothing to do." Each module is written to first check the current state of the target (a file's contents, whether a package is installed, a service's running state) and only performs an actio...

Read full answer

18. What is the difference between include and import in Ansible?

import_* (static) include_* (dynamic) Processed at playbook parse time, before the run starts. Processed at runtime, as the play executes. Tags and conditionals apply to every task inside up front. Can use variables/loops to decide what to include on the fly. Can't use a variable that's only know...

Read full answer

19. When should you use loops instead of duplicating tasks?

Whenever the same module is applied repeatedly with only the argument values changing, a loop keeps the playbook shorter and easier to maintain than writing out a near-identical task for each item. - name: Install several packages ansible.builtin.package: name: "{{ item }}" state: present loop: -...

Read full answer

20. What happens when a task fails in an Ansible playbook?

By default, when a task fails on a given host, Ansible immediately stops running further tasks against that specific host for the remainder of the play, while continuing normally on any other hosts that haven't failed. The host is marked as failed and, unless later corrected, is excluded from any...

Read full answer

21. How is variable precedence resolved in Ansible?

Because the same variable name can be set in role defaults, inventory, play vars, facts, and command-line extra vars simultaneously, Ansible defines a strict precedence order so the outcome is deterministic rather than depending on file-read order. From lowest to highest precedence (simplified): ...

Read full answer

22. Why should you avoid hardcoding secrets in playbooks?

A hardcoded password or API key in a playbook or variable file gets committed to version control history permanently - even deleting it in a later commit doesn't remove it from earlier history that anyone with repo access (or a leaked clone) can still read. Secrets in plain YAML also tend to leak...

Read full answer

23. What is the difference between Ansible and Chef/Puppet?

Ansible Chef / Puppet Agentless; connects via SSH/WinRM on demand. Agent-based; a daemon runs continuously on managed nodes. YAML playbooks, procedural-ish but declarative modules. Ruby-based DSL (Chef) or a custom declarative DSL (Puppet). Push model - control node pushes changes out. Typically ...

Read full answer

24. How does Ansible handle privilege escalation with become?

When a task or play sets become: true , Ansible connects to the managed node with the normal login user first, then invokes the configured become_method (most commonly sudo ) to re-execute the module as the target user, usually root, only for that specific task. - hosts: dbservers become: true be...

Read full answer

25. When would you choose dynamic inventory over static inventory?

A static inventory file is fine when the set of managed hosts is small and changes rarely, since manually editing a text file is simple in that case. Dynamic inventory becomes valuable once hosts are created and destroyed frequently, such as in an auto-scaling cloud environment, where a static li...

Read full answer

26. How can you optimize playbook execution speed?

Increase forks ( forks = 20 or higher in ansible.cfg) so more hosts are processed in parallel instead of the default 5. Disable unnecessary fact gathering ( gather_facts: false ) for plays that don't need host facts. Enable fact caching (e.g. to Redis or a JSON file) so repeated runs don't re-gat...

Read full answer

27. What is the difference between copy and template modules?

copy template Transfers a file as-is, byte for byte. Renders a Jinja2 template file before transferring it. Good for static files that never change per host. Good for config files that need per-host or per-environment values inserted. No templating syntax processed in the source file. Supports va...

Read full answer

28. Why do we use handlers instead of regular tasks for restarts?

A service restart is disruptive - it causes a brief outage - so it should only happen when something that actually requires it has changed, like an updated configuration file. If a restart were written as a regular task, it would run every single time the playbook executes, regardless of whether ...

Read full answer

29. How does Ansible's Jinja2 templating work in playbooks?

Jinja2 is the templating engine Ansible uses to evaluate expressions like {{ variable }} , conditionals, and loops, both directly inside playbook YAML values and inside .j2 template files processed by the template module. # Inline in a playbook - name: Show a computed value ansible.builtin.debug:...

Read full answer

30. What is the difference between roles and collections?

Role Collection A single reusable unit: tasks, handlers, templates for one purpose. A packaging format that can bundle multiple roles, modules, plugins, and docs together. Distributed individually via Ansible Galaxy. Distributed as a versioned package (also via Galaxy or private repositories). Re...

Read full answer

31. When should you use blocks with rescue in Ansible?

A block groups related tasks together, and pairing it with rescue gives Ansible try/catch-like error handling: if any task inside the block fails, execution jumps to the rescue section instead of immediately failing the whole host. - block: - name: Deploy new application version ansible.builtin.c...

Read full answer

32. How is check mode implemented in Ansible?

Check mode ( --check ) runs a playbook in a "dry run" fashion: Ansible connects to real hosts and asks each module to report what change would be made, without actually making that change on the target system. ansible-playbook site.yml --check --diff This works because well-written modules implem...

Read full answer

33. Why doesn't Ansible require a central server by default?

Ansible's core design point is that the machine running ansible-playbook , the control node , connects out to managed nodes on demand over SSH, executes what's needed, and then disconnects - there's no persistent server process that managed nodes must check in with or that the control node needs ...

Read full answer

34. What is the difference between ansible-playbook and ansible ad-hoc commands?

ansible (ad-hoc) ansible-playbook Runs a single module against hosts from the command line. Runs a YAML file describing multiple plays/tasks. Good for quick, one-off checks or fixes. Good for repeatable, version-controlled automation. Not typically saved or reused. Saved, reviewed, and re-run con...

Read full answer

35. How do you troubleshoot a failing Ansible task?

Increase verbosity ( -v , -vvv , or -vvvv ) to see the exact module arguments and, at higher levels, the raw SSH/connection details. Check the error message and module return values - most modules return a descriptive msg field explaining exactly what went wrong. Register the task's output and de...

Read full answer

36. Explain the internal working of Ansible's execution model?

Ansible's control node does the heavy lifting of assembling exactly what needs to run, then ships a minimal, self-contained payload to each target rather than relying on anything pre-installed there beyond Python. flowchart TD A[Control node parses playbook + inventory + vars] --> B[Resolve varia...

Read full answer

37. Explain the execution flow of an Ansible playbook run?

Running ansible-playbook moves through parsing, per-play host resolution, and then a repeated per-task cycle across every play in the file. flowchart TD A[Parse playbook YAML] --> B[Load inventory and variables] B --> C[For each play: resolve hosts from hosts: pattern] C --> D{gather_facts enable...

Read full answer

38. Explain the lifecycle of a task in an Ansible play?

A single task moves through templating, module dispatch, execution, and result handling before Ansible considers it complete for a given host. flowchart LR A[Task defined in play/role] --> B[Evaluate when: condition] B -- False --> C[Mark skipped] B -- True --> D[Template module arguments with Ji...

Read full answer

39. How does Ansible guarantee idempotent module behavior internally?

Idempotency isn't an engine-level guarantee that Ansible enforces automatically on arbitrary code - it's a contract that well-written modules implement internally, typically structured as a "state comparison" pattern shared across most built-in modules. # Pseudocode of typical idempotent module i...

Read full answer

40. What happens internally when Ansible gathers facts?

Fact gathering runs as an implicit task at the start of a play (unless disabled), dispatching the built-in setup module to every host in the play before any of the play's own tasks execute. flowchart TD A[Play starts, gather_facts not disabled] --> B[setup module dispatched to each host] B --> C[...

Read full answer

41. How can you optimize a large-scale Ansible deployment for performance?

Raise forks well above the default to match available control-node CPU/network capacity, so more hosts run truly in parallel. Enable persistent fact caching (Redis or similar) so a large inventory doesn't re-gather facts on every single run. Use the free strategy for independent hosts so faster h...

Read full answer

42. Which is better and why: linear or free strategy for a large inventory?

Neither is universally better; each optimizes for a different failure mode when hosts vary in speed or reliability. linear (default) free Every host must finish a task before any host moves to the next. Each host proceeds through tasks independently, as fast as it can. Predictable, easy to reason...

Read full answer

43. How does forking improve execution speed in Ansible?

By default, Ansible processes only 5 hosts at a time ( forks = 5 ); for each task, it must finish running against all currently-active hosts (up to that limit) before starting the next batch, so with a large inventory, execution time scales roughly with (number of hosts / forks) rather than shrin...

Read full answer

44. Why is idempotency critical to Ansible's module design?

Automation that isn't idempotent is dangerous to re-run: if a task blindly creates a user, appends a line to a config file, or restarts a service every single time it executes regardless of current state, running the same playbook twice can create duplicate users, duplicate config lines, or unnec...

Read full answer

45. How do you troubleshoot slow fact gathering in Ansible?

Time the gather_facts step specifically using -vvv or the profile_tasks callback to confirm it's actually the bottleneck versus other tasks. Disable gathering for plays that don't need facts ( gather_facts: false ), which is often the single biggest win if facts aren't actually used. Narrow gathe...

Read full answer

46. Explain the internal working of Ansible's variable precedence resolution?

Internally, Ansible builds up a variable's final value by layering every source that defines it, in a fixed precedence order, so the value that "wins" is whichever source sits highest in that order, regardless of the order files happen to be read from disk. flowchart TD A[Role defaults - lowest] ...

Read full answer

47. What happens when a handler is notified multiple times in a play?

Even if several different tasks across a play all call notify on the same handler name, and each of those tasks independently reports changed , Ansible still only executes that handler once , at the point handlers run (by default, at the end of the play). tasks: - name: Update main config ansible...

Read full answer

48. How does Ansible implement fact caching internally?

Fact caching stores the ansible_facts dictionary gathered for each host in an external cache backend, keyed by hostname, with a configurable time-to-live, so a future run can read cached facts instead of re-running the setup module. flowchart TD A[Play starts] --> B{Valid cache entry for host exi...

Read full answer

49. Explain the execution flow of a rolling update using serial?

serial splits a play's target hosts into smaller batches and runs the entire play (all its tasks and handlers) to completion for one batch before starting the next, instead of running each task against every host at once. flowchart TD A[Play with serial: 2 targets 6 hosts] --> B[Batch 1: hosts 1-...

Read full answer

50. How can you optimize role design to avoid duplicate work at scale?

Use run_once for cluster-wide actions - a task that only needs to happen once across the whole play (like registering a load balancer entry) shouldn't repeat per host. Cache expensive lookups - if a role queries an external API or database for shared data, fetch it once (e.g. via delegate_to on a...

Read full answer

«
»

Comments & Discussions