Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Ansible Interview Questions and Answers

By Kokil Thapa | Last reviewed: September 2026

Ansible interview questions and answers show up in nearly every DevOps, SRE, and platform-engineering screen I see in 2026. Hiring managers want proof you can automate Linux servers without turning production into a mystery script. They also want calm answers about idempotency, inventory, and failure handling. This guide maps real interview patterns to concise answers you can adapt, grounded in how Ansible runs on Ubuntu servers alongside CI/CD pipelines and Laravel deployments.

What are the most common Ansible interview questions and answers for beginners?

Junior and mid-level panels usually start with vocabulary. They want to know you understand what Ansible is before they ask you to write a playbook on a whiteboard. Keep answers short, then offer a one-line example.

What is Ansible?

Ansible is an open-source automation tool for configuration management, application deployment, and orchestration. It uses SSH to connect to remote hosts. No agent software runs on managed nodes. You write YAML playbooks. Ansible pushes changes from a control node.

On production Laravel stacks I maintain, Ansible often sits beside Linux server administration tasks: PHP-FPM pools, UFW rules, and cron paths after Deployer releases.

Why is Ansible called agentless?

Managed nodes need Python and SSH access. Ansible does not install a daemon that listens for commands. The control node runs ansible or ansible-playbook. Modules execute remotely and return JSON. That reduces attack surface and simplifies patching on small teams.

What is idempotency in Ansible?

Idempotency means running the same playbook twice produces the same end state. The second run should change nothing if the first run succeeded. Most core modules are idempotent. The command and shell modules are not unless you add creates, removes, or changed_when guards.

# Idempotent package install
- name: Ensure nginx is installed
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true

What is an Ansible inventory?

Inventory lists hosts and groups them. Static INI or YAML files work for small fleets. Dynamic inventory pulls from cloud APIs or custom scripts. Groups like web and db let you target subsets in playbooks.

[web]
web01.example.com ansible_user=deploy
web02.example.com ansible_user=deploy

[web:vars]
ansible_python_interpreter=/usr/bin/python3

For larger teams, pair inventory design with Ansible playbooks practical patterns so host variables stay readable.

Ansible Agentless ArchitectureControl Nodeansible-playbookInventoryPlaybooksSSH + PythonNo agent daemonWeb ServerApp ServerDB ServerModules run remotely and return JSON facts to the control node
Ansible interview questions and answers often start with this agentless control-node model over SSH

How do you explain Ansible architecture in an interview?

Architecture questions separate candidates who ran one playbook from those who designed automation for a fleet. Hit four components in order: control node, inventory, modules, and plugins.

What is the control node?

The control node holds playbooks, roles, and inventory. It needs Ansible installed. It does not need to be in the cloud. A GitLab CI runner or a laptop with SSH keys can act as the control node. Managed nodes never initiate connections back.

What are facts in Ansible?

Facts are variables Ansible gathers about each host at the start of a play. The setup module collects OS version, IP addresses, memory, and disk. You reference them as {{ ansible_distribution }} or {{ ansible_memtotal_mb }}. Use gather_facts: false only when speed matters and you do not need them.

What are handlers?

Handlers are tasks that run once at the end of a play, and only if notified by another task. They suit service restarts after config changes. A common pattern notifies Restart nginx only when a template task reports changed.

- name: Deploy nginx site config
  ansible.builtin.template:
    src: site.conf.j2
    dest: /etc/nginx/sites-available/app.conf
  notify: Restart nginx

handlers:
  - name: Restart nginx
    ansible.builtin.service:
      name: nginx
      state: restarted

What is Ansible Galaxy?

Galaxy is a public role repository. You install roles with ansible-galaxy install geerlingguy.php. In interviews, mention you pin role versions and review tasks before production use. Vendor roles save time but still need testing on your OS images.

Deeper role structure is covered in our Ansible roles and Galaxy guide. Sister legal-tech sites I deploy share similar role layouts across Ubuntu 22 and 24 hosts.

What Ansible playbook and module questions do interviewers ask?

Hands-on rounds ask you to read broken YAML or pick the right module. Expect loops, conditionals, tags, and error handling. Interviewers listen for safety habits, not memorized syntax alone.

Playbook structure: what belongs in a play?

A play maps hosts to tasks. Minimum keys: hosts, optional become, vars, and tasks. Roles keep plays thin. Always name tasks; unnamed tasks hurt log readability in CI output.

  1. Define inventory groups and host vars.
  2. Write roles with tasks/main.yml, handlers, templates, and defaults.
  3. Call roles from a site playbook.
  4. Run with --check on staging first.
  5. Apply tags for partial runs during incidents.

Which modules should you know cold?

Know modules for packages, files, services, users, templates, and copy. Package modules differ by OS: apt, yum, dnf. Use file for permissions. Use template for Jinja2 configs. Avoid raw shell unless no module exists.

TaskPreferred moduleInterview trap
Install nginx on Ubuntuansible.builtin.aptUsing shell: apt install breaks idempotency
Deploy config fileansible.builtin.templateForgetting notify on service restart
Ensure service runningansible.builtin.serviceNot enabling on boot with enabled: true
Run DB migration onceansible.builtin.command + run_onceRunning migration on every app node
Store API keysAnsible Vault + include_varsPlaintext secrets in Git

How do loops and conditionals work?

loop iterates a list. when skips tasks based on expressions. Combine them to install packages per group or run tasks only on Debian family hosts.

- name: Install PHP extensions
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
  loop:
    - php8.3-fpm
    - php8.3-mysql
    - php8.3-redis
  when: ansible_os_family == "Debian"

Use the JSON formatter tool when debugging module return JSON pasted from verbose runs.

Playbook Execution FlowInventoryPlayTasksModulesGather FactsCheck ModeHandlersDesired State on Managed Hostsok | changed | failed | skipped | unreachable
Interviewers expect you to walk through playbook execution from inventory to handler notification

How should you answer Ansible vs Puppet and Chef comparison questions?

Comparison questions test whether you pick tools for the job. Ansible is push-based and agentless. Puppet and Chef traditionally run agents and enforce desired state on a schedule. Salt can do both. None replaces a full Terraform versus Ansible strategy discussion.

CriteriaAnsiblePuppetChef
Agent on nodesNo (SSH)YesYes
LanguageYAML + Jinja2Puppet DSLRuby recipes
Learning curveLower for ops teamsSteeper DSLRequires Ruby comfort
Best fitAd-hoc and CM pushesLarge enforced fleetsComplex policy code
Typical pairingTerraform for infraLegacy enterprise DCLegacy enterprise DC

Strong answer: "I use Terraform to create VPCs, security groups, and EC2 instances. Ansible configures those instances with users, packages, and app settings. They complement each other." That aligns with how I provision PHP stacks before automating server setup with Ansible.

For a wider tooling lens, read Ansible vs Puppet vs Chef vs Salt and DevOps engineer interview prep.

Ansible vs shell scripts: what is your answer?

Shell scripts run imperative steps once. Ansible declares desired state with idempotent modules. Scripts are fine for one-off fixes. Playbooks belong in Git, run in CI, and scale across groups. Mention --check dry runs as a safety net scripts rarely offer.

Push vs Agent-Based CMAnsible PushControlHost AHost BAgent Pull ModelMasterAgentAgentAnsible SSH push vs scheduled agent convergence on managed nodes
Ansible interview questions and answers on tooling differences often reference this push versus agent pull split

What advanced Ansible interview questions appear in senior DevOps roles?

Senior loops cover Vault, performance, delegation, testing, and failure recovery. Interviewers want production scars: partial deploys, stale cron paths, and secret rotation without downtime.

How does Ansible Vault work?

Vault encrypts sensitive files or variable strings with AES. You create a password file or use a script for CI. Encrypted content starts with $ANSIBLE_VAULT;. Decrypt at runtime with --ask-vault-pass or ANSIBLE_VAULT_PASSWORD_FILE.

# Encrypt a vars file
ansible-vault encrypt group_vars/web/vault.yml

# Edit in place
ansible-vault edit group_vars/web/vault.yml

# Run playbook with vault
ansible-playbook site.yml --vault-password-file ~/.vault_pass

See Ansible Vault for secrets and encrypt secrets in playbooks for patterns I use on shared EC2 fleets. Official docs live at Ansible Vault user guide.

What is ansible-pull?

ansible-pull runs playbooks on the managed node itself. The node clones a Git repo and applies locally. Use it when no persistent control node exists. Edge cases and golden AMI bootstrapping sometimes need this pattern.

How do you speed up large playbook runs?

  • Set forks in ansible.cfg for parallel SSH sessions.
  • Use strategy: free when task order per host is loose.
  • Disable fact gathering when facts are unused.
  • Apply tags to run subset tasks during hotfixes.
  • Cache facts with fact caching for repeated CI runs.

How do you test Ansible changes?

Use Molecule with Docker or Vagrant drivers for role tests. Run ansible-playbook --syntax-check in CI. Run --check --diff against staging. Lint with ansible-lint. Pin collections in requirements.yml. These steps mirror how I gate deploys before touching production PHP-FPM pools.

Pair automation testing with testing and optimization practices and infrastructure work on projects like Adventure Third Pole Trek, where Laravel plus Livewire runs on tuned Ubuntu hosts.

Scenario: deploy failed mid-playbook. What do you do?

First, read the failure task and host name in output. Fix the root cause: package mirror down, bad variable, permission error. Re-run with the failing tag or from the failed task using --start-at-task. If partial config broke a service, roll back with a known-good playbook version from Git. Mention you never edit live servers by hand without back-filling the playbook afterward.

Ansible Vault Secrets WorkflowPlain SecretsAPI keys, DB passansible-vaultGit Repoencrypted filesCI / Control Nodevault password filePlaybook Runvars injected safelyNever commit vault passwords; rotate keys on staff changes
Senior Ansible interview questions and answers frequently drill Vault encrypt-store-decrypt workflow

Scenario: provision a LAMP stack for Laravel

Interviewers may ask for a high-level playbook outline. Structure your answer around roles, not one giant task list.

---
- name: Configure web tier for Laravel
  hosts: web
  become: true
  roles:
    - role: geerlingguy.php-versions
      vars:
        php_version: "8.3"
    - role: geerlingguy.php
    - role: geerlingguy.mysql
    - role: geerlingguy.nginx
  tasks:
    - name: Ensure laravel queue worker systemd unit
      ansible.builtin.template:
        src: laravel-worker.service.j2
        dest: /etc/systemd/system/laravel-worker.service
      notify: Reload systemd

Mention Ansible playbooks for PHP server provisioning and PHP 8.3 minimums for Laravel 13. Cite the official playbook keywords reference if asked about valid keys.

What is the difference between delegate_to and local_action?

delegate_to runs a task on a different host than the current loop item. Use it to add a load-balancer node from an app server play. local_action is shorthand for delegate_to: localhost. Common for API calls or cloud modules that should not run on remote hosts.

How does Ansible fit with Docker and Kubernetes?

Ansible can install Docker, compose stacks, and configure kubelet on bare nodes. Day-two cluster work often shifts to Helm or operators. In interviews, say Ansible excels at node and VM configuration. Kubernetes handles container scheduling. Cross-read Docker interview questions and Kubernetes interview questions for adjacent panels.

For Linux fundamentals that underpin SSH automation, review Linux interview questions for DevOps. Terraform-focused peers should scan Terraform interview questions since many teams split provisioning and CM across both tools per the HashiCorp automate Terraform guide.

Key Takeaways

  • Lead with agentless SSH, YAML playbooks, and idempotent modules — interviewers treat these as non-negotiable basics.
  • Explain handlers, facts, inventory groups, and roles with one concrete nginx or PHP example from your experience.
  • Position Ansible as configuration management paired with Terraform for infrastructure creation, not as a replacement.
  • Always mention Vault for secrets, --check for dry runs, and tags for safe partial reruns after failures.
  • Practice scenario answers: mid-playbook failure, secret rotation, and provisioning a web stack for a Laravel app.
  • Run ansible-lint and Molecule in CI before claiming your playbooks are production-ready.

People Also Ask

Is Ansible still worth learning in 2026?

Yes. Ansible remains widely used for server configuration, VM bootstrap, and network automation. Cloud-native teams still need day-two patching, user management, and app config. Ansible skills transfer to AWX and Automation Controller jobs at enterprises standardizing on Red Hat tooling.

What Ansible topics appear most in interviews?

Expect idempotency, inventory, playbooks versus roles, common modules, handlers, Vault, variables precedence, conditionals, loops, and Ansible versus Terraform boundaries. Senior roles add performance tuning, testing, and incident-style scenario questions.

How do I prepare for a hands-on Ansible interview?

Build a small project: three Ubuntu VMs, a role that installs nginx and deploys a static site, Vault-encrypted vars, and a GitLab CI job running syntax-check and ansible-lint. Be ready to explain every task aloud in under two minutes.

Does Ansible require Python on remote hosts?

Most modules need Python on the target. Minimal images may lack it. Use the raw module or a bootstrap task to install Python first. Windows targets use WinRM instead of SSH. State this clearly; interviewers use it to probe edge-case awareness.

Prepare your next DevOps interview with confidence

Strong Ansible interview questions and answers come from running playbooks on real servers, not from flashcards alone. Build one role, break it in staging, fix idempotency gaps, and encrypt every secret with Vault. If you want help automating Ubuntu fleets for Laravel, WordPress, or legal-tech portals, review our support and maintenance services or browse the portfolio for deployed examples. Need a walkthrough of your stack? Contact us and we can map an Ansible path that fits your team size and budget.

Frequently Asked Questions

Ansible is an open-source automation tool for configuration management, application deployment, and orchestration. You write YAML playbooks on a control node and push changes over SSH to managed hosts. No agent software runs on target servers, which keeps patching and security simpler on small teams.

Managed nodes only need SSH access and Python. Ansible does not install a daemon that listens for commands. The control node runs ansible or ansible-playbook, modules execute remotely, return JSON, and exit. That reduces attack surface compared with Puppet or Chef, where agents enforce state on a schedule.

Idempotency means running the same playbook twice reaches the same end state; the second run should change nothing if the first succeeded. Most core modules like apt, template, and service are idempotent. command and shell are not unless you add creates, removes, or changed_when guards.

Inventory lists hosts and groups them for targeting in playbooks. Small fleets use static INI or YAML files; larger setups use dynamic inventory from cloud APIs or custom scripts. Groups like web and db let you run tasks on subsets, with host vars such as ansible_user and ansible_python_interpreter defined per group.

Hit four parts in order: the control node holding playbooks, roles, and inventory; inventory defining hosts and groups; modules performing work on remote hosts; and plugins extending behavior. The control node initiates all connections. Managed nodes never call back. A GitLab CI runner or laptop with SSH keys can act as the control node.

Facts are variables Ansible gathers about each host at play start via the setup module. They include OS family, distribution, IP addresses, memory, and disk details. Reference them in tasks and conditionals as ansible_distribution or ansible_memtotal_mb. Set gather_facts: false only when speed matters and you already know what you need.

Handlers are tasks that run once at the end of a play, and only if another task notifies them. They suit service restarts after config changes. A common pattern deploys an nginx site template, notifies Restart nginx when the file changes, and the handler restarts the service once even if multiple tasks notify it.

Galaxy is Ansible's public role repository. You install community roles with ansible-galaxy install, for example geerlingguy.php, to avoid rewriting common server setup. In interviews, state that you pin role versions, review tasks before production, and test vendor roles against your Ubuntu images. Galaxy saves time but does not replace validation.

Know apt, yum, and dnf for packages; file for permissions; template for Jinja2 configs; copy for static files; service for daemons with enabled: true; and user for accounts. Use template plus notify for config deploys. Reserve command or shell for cases with no module, such as a one-time DB migration with run_once. Store secrets with Ansible Vault, never plaintext in Git.

loop iterates a list, running a task once per item, such as installing multiple PHP extensions. when skips tasks based on expressions, like running apt tasks only when ansible_os_family equals Debian. Combine both to install packages per group or limit tasks to specific OS families without duplicating entire plays.

Ansible is push-based and agentless over SSH with YAML playbooks. Puppet and Chef traditionally run agents on nodes and enforce desired state on a schedule. Ansible suits ad-hoc pushes and configuration management for ops teams with a lower learning curve. Puppet and Chef fit large fleets with enforced policy code. None replaces Terraform for infrastructure creation.

Terraform provisions infrastructure: VPCs, security groups, EC2 instances, and other cloud resources. Ansible configures those instances with users, packages, PHP-FPM pools, nginx, and application settings. They complement each other. Strong answer: Terraform creates the servers; Ansible makes them ready for a Laravel or PHP stack. Do not position Ansible as a full replacement for provisioning tools.

Vault encrypts sensitive files or variable strings with AES. Encrypted content starts with $ANSIBLE_VAULT;. Create or edit files with ansible-vault encrypt or ansible-vault edit. At runtime, decrypt with --ask-vault-pass or ANSIBLE_VAULT_PASSWORD_FILE for CI. Use it for API keys and database passwords in group_vars instead of storing secrets in plain Git.

Read the failing task name and host in the output first. Fix the root cause, whether a mirror outage, bad variable, or permission error. Re-run with a tag for the failed section or --start-at-task to avoid repeating successful steps. If partial config broke a service, roll back using a known-good playbook version from Git. Never hand-edit production without back-filling the playbook.

Raise forks in ansible.cfg for parallel SSH, use strategy: free when task order per host is loose, disable fact gathering when unused, apply tags for partial runs, and cache facts for repeated CI jobs. Test with ansible-playbook --syntax-check, ansible-lint, Molecule for roles, and --check --diff against staging. Pin collections in requirements.yml the same way you gate Deployer releases before touching PHP-FPM pools.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: