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

Members can save this page, take notes and track progress. See membership · Sign in

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.user instead of useradd).
  • For command/shell, add creates: or removes: 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), and failed_when: for commands with unusual exit codes.
  • Use state: present/absent/started rather than actions such as "install" or "restart".
  • Run in check mode (--check --diff) to see what would change; an idempotent playbook's second run reports changed=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/shell need creates, removes or changed_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

← All Ansible questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake