Ansible and Infrastructure as Code: Idempotency and Best Practices
Idempotent Ansible means you can run a playbook twice and the second run does nothing. Here is how we get there, and where we stopped fighting it.
Key takeaways
- An idempotent Ansible playbook can run any number of times and the second run reports no changes, because modules converge on a desired state instead of replaying steps.
- Prefer modules over shell, guard commands with creates and changed_when, gate restarts behind handlers, and run Molecule's idempotence step in CI.
On this page
An idempotent Ansible playbook is one you can run ten times with the same result as running it once: the second run reports changed=0 because the machine already matches what you described. You get there by using modules instead of shell, guarding unavoidable commands with creates and changed_when, restarting through handlers, and testing the second run in CI.
Verified againstChecked against official docs
ansible-core 2.21 (2.21.5, in the Ansible 14 package), Molecule 26.10.0, against the docs.ansible.com check mode, command module and Molecule configuration pages. Checked October 2026.
Our first production playbook was a mess of shell: tasks that ran fine the first time and broke the second. One appended a line to a config file: run it three times, three lines, and nginx stopped starting. Write for the second run.
What idempotency actually means
Idempotency is the property that applying an operation once has the same result as applying it many times. Set a file's mode to 0644. It is already 0644? Then the module does nothing and reports ok. It was 0600? The module changes it and reports changed. Either way you end up in the same place, and the module tells you honestly which of the two happened.
That honesty is the point. You are almost never building a machine from scratch; you are reconciling a running box against a description. Without idempotency you cannot tell "I fixed drift" apart from "I trampled a config that was already fine."
How modules get you this for free
Ansible's native modules converge on a state, not on steps. You do not tell ansible.builtin.copy to copy a file; you tell it the file should have this content and these permissions. It checks, then acts only if reality disagrees.
- name: Ensure nginx config is present
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: "0644"
notify: Reload nginx
On a box that already has the rendered file it reports ok. Change the template and only then do you see changed and a handler firing. Compare the trap we fell into:
# roles/nginx/tasks/main.yml (don't do this: appends every single run)
- name: Add upstream to config
ansible.builtin.shell: echo "upstream app { server 10.0.0.5; }" >> /etc/nginx/nginx.conf
shell and command have no idea what state they are supposed to produce. They run the string you gave them, every time, and report changed every time because from their point of view they did do work.
Making command and shell behave
Sometimes you genuinely need to shell out. There is no module for the weird vendor CLI, or the operation is a one-shot. You can still make those tasks honest with creates, removes, and changed_when.
- name: Initialize the database schema once
ansible.builtin.command: /opt/app/bin/migrate --init
args:
creates: /var/lib/app/.schema_initialized
- name: Check cluster health without ever reporting changed
ansible.builtin.command: /usr/local/bin/cluster status
register: cluster
changed_when: false
failed_when: "'healthy' not in cluster.stdout"
The creates guard means the migration runs once and is skipped forever after, because the marker file exists. changed_when: false tells Ansible this is a read, not a write, so it never pollutes your change count. These knobs turn a lying task into a truthful one. If you use shell, use them.
Check mode and diff before you touch anything
Before applying a playbook to anything that matters, run it in check mode. --check does a dry run: modules report what they would change without changing it. Pair it with --diff and you see the exact lines a template would rewrite.
ansible-playbook site.yml --check --diff --limit web-prod-01
This is only as good as your modules, though. The command module docs list its check mode support as partial: the command itself is arbitrary, so Ansible skips it in check mode unless creates or removes gives it something to predict from. Yet another reason to prefer modules: they make your dry run mean something.
Structure: roles and reuse
A single 800-line playbook is a smell. Once one grows past a screen or two, break it into roles. A role bundles tasks, handlers, templates, defaults, and variables under a fixed directory layout, and you include it by name. The nginx role sets up nginx; the app role deploys the app; the site playbook just lists which roles run on which hosts.
The payoff is reuse: the same postgres role serves staging and production with different variables. Keep roles focused on one thing, put sane values in defaults/main.yml, and let callers override what they need.
Variables and inventory
Ansible's variable precedence is deep, and fighting it causes real pain. The short version: role defaults sit at the bottom, group vars above them, host vars above those, and command-line -e extra vars win over everything. Set broad defaults low and narrow overrides high.
Group hosts by role and environment (webservers, prod) and let group_vars/ and host_vars/ carry the values. Keep environment differences in group vars, not in the tasks, so the same role runs everywhere.
Handlers and notify
Handlers are how you avoid needless restarts. A handler only runs if a task notifys it, and only once at the end of the play no matter how many tasks poked it.
# site.yml (excerpt)
tasks:
- name: Deploy vhost
ansible.builtin.template:
src: vhost.conf.j2
dest: /etc/nginx/conf.d/app.conf
notify: Reload nginx
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
Change the template on ten hosts and nginx reloads on those ten. Change nothing and nginx is left alone. That is idempotency at the service level.
Secrets with Vault
Do not commit plaintext secrets, and do not pass them around as extra vars in your shell history. Ansible Vault encrypts values or whole files at rest with a password or key.
ansible-vault encrypt_string 's3cr3t-db-pass' --name db_password
That drops an encrypted blob into a vars file. Playbooks reference db_password normally; Ansible decrypts at runtime when you supply the vault password. Encrypt individual strings inside otherwise readable vars files so diffs stay meaningful, and keep the vault password in a real secret store, not next to the repo.
Testing: molecule and the idempotence check
The single most useful test for a role is the idempotence test, and it is almost free. Run the role, then run it again and assert the second run reports zero changes. Anything that comes back changed on the second pass is a non-idempotent task hiding somewhere.
Molecule automates this: it spins up a test instance, applies the role, and then applies it again in the idempotence step. That step is part of Molecule's default test sequence, so molecule test runs it without extra config. A trimmed sequence looks like this:
# molecule/default/molecule.yml (trimmed)
scenario:
test_sequence:
- create
- converge # first apply
- idempotence # second apply must report no changes
- verify
- destroy
That idempotence step is the guardrail. Wire it into CI and a shell task without changed_when will fail the build, which is exactly what you want it to do.
Ansible vs Terraform
People treat these as rivals. They are not. Terraform provisions infrastructure: it talks to cloud APIs, tracks state, and creates or destroys the VMs, networks, and load balancers. Ansible configures things that already exist. It SSHes into a box and reconciles packages, files, and services. If your Terraform modules are shared across teams, versioning Terraform modules in shared registries covers how to keep them from breaking consumers, and Ansible vs Terraform goes deeper on the split.
The clean split we use: Terraform stands up the machines and the network; Ansible dresses them once they exist. Terraform's state file is its source of truth. Ansible has no state file, which is exactly why idempotency matters so much for it: the running machine is the only truth it has.
Questions people ask
What does idempotent mean in Ansible?
It means running a task or playbook again leaves the system unchanged once it is already in the desired state. Native modules such as ansible.builtin.template or ansible.builtin.service check the current state first and report ok when nothing needs doing, or changed when they had to act. A playbook is idempotent when its second run reports changed=0 across every host.
How do I make shell and command tasks idempotent?
Give Ansible a way to know whether work is needed. Use creates to skip a command once a marker file exists, or removes to run it only while a file exists. For read-only commands set changed_when: false, and for commands that do change things, set changed_when from their output. Better still, look for a module that does the job; one usually exists.
The call we'd make
Write for the second run, not the first. Prefer modules, and when you must shell out, tell Ansible the truth with creates and changed_when. Split work into small roles, keep environment differences in inventory, gate restarts behind handlers, and put an idempotence test in CI so the machine catches the drift you will not. Use Terraform to build the boxes and Ansible to configure them, and stop pretending either one wants to do the other's job. Do that and your playbooks become boring, which in infrastructure is the highest compliment there is.
Sources
Cite this article
Kiril Urbonas (2026). Ansible and Infrastructure as Code: Idempotency and Best Practices. DevOpsNess. Updated 2026-11-20. https://www.devopsness.com/blog/ansible-and-infrastructure-as-code-idempotency-and-best-practices
[Ansible and Infrastructure as Code: Idempotency and Best Practices](https://www.devopsness.com/blog/ansible-and-infrastructure-as-code-idempotency-and-best-practices) (Kiril Urbonas, DevOpsNess, updated 2026-11-20)
More from Infrastructure
Explore more articles in this category
Infrastructure Documentation as Code: How One Platform Team Reduced Audit Fire Drills
This infrastructure documentation as code guide shows how a platform team moved runbooks, ownership maps, and architecture decisions into versioned workflows that people actually trusted.
Backstage Software Catalog: Getting Adoption Past the Demo
The Backstage demo always wows leadership. Then six months later the catalog has 400 stale entries and nobody trusts it. Here's what got ours to actually stick.
Disaster Recovery Planning: Building Resilient Infrastructure
A different angle on DR: the planning process — RTO/RPO conversations, dependency mapping, and what we learned about prioritizing what to recover.
You might have missed
Evergreen posts worth revisiting.