Interview › Infrastructure as Code (Terraform, Ansible)
What is idempotency in Ansible, and why does it matter?
Infrastructure as Code (Terraform, Ansible) · Intermediate level
Answer
Idempotency means running the same automation multiple times should produce the same final state without unnecessary changes. In Ansible, idempotent modules report changed only when they actually modify the host, which makes repeated runs safe and enables reliable handlers and drift correction.
Technical explanation
Idempotency is what makes configuration management safe as a recurring operation.
Handlers rely on correct changed status; false changes can cause unnecessary restarts.
Idempotent playbooks are easier to run in CI, during incidents, and on schedules.
Prefer idempotent modules over shell so repeated runs are safe and change reporting is meaningful.
Separate reusable role logic from inventory-specific variables so the same automation works across environments.
Run lint, syntax checks, check mode where useful, and staged rollouts before production-wide changes.
Hands-on example
1. Make a task idempotent for: What is idempotency in Ansible, and why does it matter?
2. Replace an unsafe command with a module where possible:
- name: Install nginx idempotently
ansible.builtin.package:
name: nginx
state: present3. If command is unavoidable, add guards:
- name: Initialize application database once
ansible.builtin.command: /opt/app/bin/init-db
args:
creates: /var/lib/app/.db_initialized
register: init_result
changed_when: init_result.rc == 04. Run the playbook twice; the second run should report ok rather than changed for already-converged tasks.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is a playbook, a play, and a task?
- Why is a raw shell or command task not idempotent, and how do you make it safe?
- What is an Ansible inventory, and what is the difference between static and dynamic inventory?
- What is the creates argument on a command task, and how does it add idempotency?
- How does Ansible connect to managed hosts?
- What are Ansible modules, and why prefer them over shell commands?
- What is Ansible, and how is it agentless?
- What is a handler, and how is it triggered with notify?