Interview › Infrastructure as Code (Terraform, Ansible)
Why is a raw shell or command task not idempotent, and how do you make it safe?
Infrastructure as Code (Terraform, Ansible) · Intermediate level
Answer
Raw shell or command tasks are not inherently idempotent because Ansible cannot know whether the command changed anything. You make them safer with creates, removes, changed_when, failed_when, check_mode guards, or by replacing them with a purpose-built module.
Technical explanation
A command might create a user, append a line, or restart a service every time unless guarded.
Use modules such as package, service, lineinfile, copy, template, user, and file when possible.
If command is unavoidable, explicitly define changed_when and failed_when.
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: Why is a raw shell or command task not idempotent, and how do you make it safe?
2. Replace an unsafe command with a module where possible:
- name: Install nginx idempotently
ansible.builtin.package:
name: nginx
state: present
3. 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 == 0
4. 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 Infrastructure as Code, and what problems does it solve over click-ops?
- What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
- What is the difference between configuration management and provisioning?
- What is Terraform, and what is the core plan/apply workflow?
- What does terraform init do?
- What is the Terraform state file, and why is it critical?
- Why should state be stored remotely, and what backend would you use on AWS?
- What is state locking, and why does it matter for teams?