Ansible interview question · Most asked
What is idempotency in Ansible, and how do you keep your own tasks idempotent?
Definition Asked in DevOps Engineer interviews
Summary
An idempotent task can run any number of times and leaves the host in the same state, reporting changed only
when it actually changed something. Built-in modules (apt, template, service, user) are idempotent
because they compare the desired state with the current one. Tasks built on command or shell are not, unless
you make them so.
Longer Answer
Idempotency is what makes it safe to re-run a playbook after a failure, run it on a schedule to correct drift,
and trust the changed count as a signal.
Ways to keep tasks idempotent:
- Prefer a real module over
shell(ansible.builtin.userinstead ofuseradd). - For
command/shell, addcreates:orremoves:so it is skipped when the result already exists. - Use
changed_when:to report change accurately (for example, only when the output says something changed), andfailed_when:for commands with unusual exit codes. - Use
state: present/absent/startedrather than actions such as "install" or "restart". - Run in check mode (
--check --diff) to see what would change; an idempotent playbook's second run reportschanged=0.
Example
- name: Initialise the app database once
ansible.builtin.command: /opt/app/bin/init-db
args:
creates: /var/lib/app/.db-initialised
- name: Check migration status
ansible.builtin.command: /opt/app/bin/migrate --status
register: status
changed_when: false # reading state never changes anything
Key Points
- Same result however many times it runs.
- Modules compare desired and current state.
command/shellneedcreates,removesorchanged_when.- A second run should report changed=0.
Explanation
What interviewers look for
Knowing why it matters (safe re-runs, drift correction) and the concrete tools for shell tasks: creates, changed_when and check mode.
More Ansible questions
- Write an Ansible playbook that installs Nginx, deploys its configuration, enables the service and restarts it only when the configuration changes.
- Explain Ansible's architecture: control node, inventory, modules, playbooks, roles and handlers.
- How do you structure reusable Ansible roles for several environments?
- Explain serial, delegate_to, when and notify in Ansible.
- How would you automate TLS certificate installation and renewal with Ansible?
- How would you configure 100 Linux servers consistently with Ansible?
- How do Ansible and Terraform work together in one delivery pipeline?
- A playbook run fails halfway through 50 hosts. What do you do?