Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 29 ยท Practice and Review

Interview Questions

Prepare for an Ansible interview: concepts, idempotence, roles vs collections, vault, handlers, variable precedence, scenarios and troubleshooting questions with clear answers.

Ansible interviews tend to test the same few ideas from different angles: do you understand why Ansible works the way it does, can you write something safe and repeatable, and can you find your way out of a failure? This page collects the questions that come up most often, with answers short enough to say aloud. They are grouped from fundamentals to scenarios.

Everything in the answers is explanation, so the commands and YAML are read-only. Two runnable stand-ins, written in JavaScript, turn the two most-asked topics (idempotence and handlers) into something you can run and show on a whiteboard. They are models of Ansible's behaviour, not Ansible itself.

A tip for any interview: answer in three steps. State the definition in one sentence, give a small example, then mention one trade-off or pitfall. That pattern shows depth without rambling.

Fundamentals

What is Ansible, and how is it different from a shell script?

Ansible is an automation tool for configuration management, application deployment and orchestration. You describe the desired state of machines in YAML, and Ansible makes them match. A script describes steps and repeats them blindly; Ansible's modules first check the current state and change only what differs. See What Is Ansible?.

What does "agentless" mean?

Nothing needs to be installed on managed nodes except an SSH server and, for most modules, Python. The control node pushes small programs over SSH (WinRM for Windows), runs them and collects the result. Compared with agent-based tools such as Puppet or Chef, this removes a daemon to install, patch and secure, at the cost of a push model that relies on connectivity at run time.

What are the control node and managed nodes?

The control node is the machine where you run ansible and ansible-playbook: a laptop, a CI runner or an AWX server. Managed nodes (hosts) are the machines Ansible configures. Control nodes need Linux or macOS (or WSL on Windows); Windows machines are managed nodes only.

What is an inventory?

A list of hosts and groups, in INI or YAML, or generated dynamically from a cloud API. Variables can be attached to hosts and groups, and group_vars/ and host_vars/ directories keep them out of the inventory file. Groups can contain other groups with :children. See Inventory: Hosts and Groups.

What is the difference between an ad-hoc command and a playbook?

An ad-hoc command (ansible web -m ansible.builtin.ping) runs one module once, which suits quick checks and one-off jobs. A playbook is a versioned YAML file with plays and tasks that you can review, repeat and test. Anything you will do twice belongs in a playbook.

What are plays, tasks and modules?

A playbook is a list of plays. A play maps a group of hosts to a list of tasks. Each task calls one module, the unit of work that runs on the managed node and reports ok, changed, failed or skipped.

Idempotence and modules

What is idempotence, and why does it matter?

An operation is idempotent if running it once or many times leaves the system in the same state. It lets you run a playbook on a schedule, after a partial failure or on a new machine without fear, and it makes changed=0 on the second run a meaningful health check. Modules achieve it by comparing state before acting.

JS Idempotence in a few lines

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The declarative function reports two changes on the first run and none afterwards. The step function keeps "changing" forever, which is exactly what a naive script does.

Which modules are not idempotent by default?

command, shell, raw and script. Ansible cannot know what an arbitrary program did, so it reports changed every time. You make them honest with creates, removes, changed_when and failed_when. See Modules and Idempotence.

What is the difference between command, shell and raw?

command runs a program directly with no shell, so there are no pipes or variable expansion, which makes it the safest choice. shell goes through /bin/sh and supports pipes and redirects. raw sends the string over SSH without a module, so it needs no Python on the target; use it only to bootstrap.

What does check mode do, and what are its limits?

--check asks modules to predict their changes without applying them, and --diff shows file differences. Limits: command-style tasks cannot predict anything (they are skipped unless creates or removes decides), and a task that depends on an earlier task's real effect, such as starting a service from a package that "would have been" installed, can fail in check mode.

How do you control what counts as changed or failed?

changed_when and failed_when take expressions that can use the registered result, for example changed_when: "'Applied' in migrate.stdout" or failed_when: result.rc not in [0, 2]. changed_when: false marks pure read-only commands.

Variables, templates and logic

Where can variables be defined, and which wins?

Role defaults, inventory and group_vars/host_vars, play vars and vars_files, role vars, task vars, set_fact and register, and extra vars (-e). A rough order from weakest to strongest: role defaults, group vars, host vars, play vars, role vars, set_fact and register, extra vars. A host beats its groups, a more specific group beats a more general one, and -e beats everything. See Variables, Facts and Precedence.

What are facts?

Variables that Ansible gathers about each host at the start of a play (operating system, network interfaces, memory and more) through the setup module. Read them as ansible_facts['os_family']. You can turn gathering off with gather_facts: false to save time, or cache facts between runs.

What is the difference between register and set_fact?

register stores a task's result in a variable. set_fact creates or changes a variable from an expression. Both are per host and last for the rest of the play (and with fact caching, longer for set_fact).

How do loop and when work together?

when is evaluated separately for each item, so a condition can use item. Loops over a registered result use result.results. The older with_items keywords still work but loop is the modern form.

What is Jinja2 used for in Ansible?

In two places: inside playbook values ("{{ http_port }}" and filters such as default, join, map and to_json) and in template files (.j2) rendered by the template module, where {% for %} and {% if %} generate config files. A value that starts with a brace must be quoted in YAML.

Structure: handlers, roles, collections

What is a handler?

A task that runs only when notified by another task that reported changed, and only once per host at the end of the play, even if notified many times. The usual use is restarting or reloading a service after its config changed. meta: flush_handlers runs the pending handlers early.

JS Handlers: notified many times, run once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that with flush_handlers, restart nginx runs twice: once at the flush, and again at the end because a later task notified it again. If that matters, flush after the last task that notifies it.

What is a role, and how does it differ from a playbook?

A role is a directory with a fixed layout (tasks, handlers, defaults, vars, templates, files, meta) that packages reusable automation. A playbook decides which hosts get which roles. Roles keep playbooks short and share code between projects. See Roles and Project Layout.

What is the difference between defaults and vars in a role?

defaults/main.yml has the lowest precedence and is meant to be overridden by the caller. vars/main.yml has high precedence and is for internal constants that callers should not change.

What is a collection, and how does it differ from a role?

A collection is a distribution format that can contain modules, plugins, roles and playbooks, with a namespace and a version (community.general). A role contains tasks and files only. Use FQCN module names such as ansible.builtin.copy so it is clear where a module comes from, install collections with ansible-galaxy collection install and pin them in requirements.yml. See Collections, Galaxy and Reusable Content.

What is the difference between import_tasks and include_tasks?

import_* is static: it is processed when the playbook is parsed, so tags and when apply to every imported task, and the imported file cannot use loop variables. include_* is dynamic: it is processed at run time, so it can be looped over or chosen with a variable, but tags on the include itself do not reach the tasks inside.

What are tags?

Labels on tasks, plays or roles. --tags deploy runs only matching tasks and --skip-tags skips them, which is useful for running part of a large playbook. always and never are special tags.

Secrets and security

How do you handle secrets?

With Ansible Vault: ansible-vault encrypt or create for whole files, encrypt_string for single values, and --ask-vault-pass, --vault-password-file or vault IDs at run time. Use no_log: true on tasks that handle secrets so values stay out of output, and keep the vault password out of the repository. For stricter needs, read secrets from an external system through a lookup plugin. See Ansible Vault and Secrets.

What is become?

Privilege escalation. become: true runs a task as root (through sudo by default); become_user picks another user and become_method another mechanism. Apply it only where needed, and give the connecting user the narrowest sudo rights that work.

How does Ansible authenticate to hosts?

By SSH keys (preferred), an SSH agent or passwords, using ansible_user and ansible_ssh_private_key_file or the matching play keywords. Windows uses WinRM or SSH. Host key checking should stay on; see SSH, Privilege Escalation and Hardening.

Scenarios and troubleshooting

A playbook reports changed on every run. What do you do?

Run with --diff to see what it keeps changing. The usual causes are a command or shell task with no guard, a template that renders something different each time (a timestamp, an unordered dictionary), or a module argument that the system normalises (such as a file mode or a package version). Add creates or changed_when, make the template deterministic and use values in the form the system reports.

You have 500 servers and the play is slow. How do you speed it up?

Raise forks above the default of 5, turn on SSH pipelining, set gather_facts: false or cache facts when you do not need them, use strategy: free if hosts do not depend on each other, use async for long tasks, prefer one package task with a list over a loop and keep inventory plugins fast. See Performance, Dynamic Inventory and AWX.

How would you do a zero-downtime rolling update?

Use serial to update a few hosts at a time, delegate_to the load balancer to drain each host first, run a health check with until and retries after the update, and stop the rollout when a batch fails with max_fail_percentage or any_errors_fatal. See Ansible with Docker, Terraform and CI/CD.

What do you do when a host is UNREACHABLE?

Try the same SSH command by hand. Then check the address and user with ansible-inventory --host, the key, known_hosts and the network, and add -vvv to see the exact SSH command. See Common Mistakes and Troubleshooting.

How do you test Ansible code?

At several levels: --syntax-check, yamllint and ansible-lint for static checks; --check --diff against a real inventory; Molecule with containers or virtual machines for role tests (converge, idempotence, verify); and a CI pipeline that runs all of it on every change. See Testing, Linting and Debugging.

Ansible or Terraform?

They overlap less than people think. Terraform (or OpenTofu) is declarative infrastructure provisioning that keeps state and plans changes; Ansible is strongest at configuring what is inside machines and at orchestrating steps. A common pattern is Terraform to create servers and Ansible to configure them. See Automation with Ansible and Terraform.

How do you stop a secret from leaking into logs?

Use no_log: true on the task, avoid -vvv on runs that handle secrets, keep secrets in vault files and never pass them on the command line where they land in shell history and process lists.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is ansible.builtin.shell: useradd deploy a weaker choice than the user module?

    Modules compare state before acting. A shell command repeats its action and Ansible can only guess whether anything changed.
  2. 2. A task notifies the handler 'restart nginx' three times on one host, and all three tasks changed something. How many times does the handler run at the end of the play on that host?

    Handlers are deduplicated per host and run once, after the tasks, unless flush_handlers runs them earlier.
  3. 3. Which describes import_tasks correctly?

    import_* is static, so tags and conditions apply to each imported task. include_* is dynamic and evaluated when the task runs.
  4. 4. Which is the strongest variable layer?

    Extra vars beat every other source, which makes them handy for one-off overrides and dangerous as a habit.
  5. 5. What is the most useful first step when a task reports changed on every run?

    --diff shows the difference that keeps being applied. It points to an unguarded command, a non-deterministic template or a value the system normalises.

Summary

  • Explain Ansible as an agentless, push-based tool that describes desired state and gets idempotence from modules that compare before acting.
  • Know the vocabulary: control node, managed node, inventory, play, task, module, role, collection, handler, fact.
  • command, shell, raw and script are not idempotent by default; creates, removes and changed_when fix that.
  • Handlers run once per host at the end of a play, only after a real change; flush_handlers runs them earlier.
  • Extra vars beat everything; a host beats its groups; role defaults are the weakest layer.
  • Use Vault and no_log for secrets, become with least privilege, and serial with health checks for rolling updates.
  • For scenario questions, diagnose in order: parse errors, connection, privilege, module arguments, then logic and precedence.

Next: Ansible Cheat Sheet