DevopsIntermediate

Ansible Tips: Best Practices and Essential Resources

Admin KC
5 min read

TL;DR

A curated reference guide to mastering Ansible: official documentation, best practices, Galaxy roles, security with Vault, and testing strategies.

Ansible Tips: Best Practices and Essential Resources

Executive Summary

Ansible fails in production for boring reasons: playbooks that only run once, secrets committed to git, roles copied between projects until nobody knows which copy is real. The teams that run Ansible well treat playbooks like software — versioned, tested, idempotent, and boring to re-run. This guide collects the practices that separate a weekend automation script from infrastructure you can trust at 3 AM: structure, idempotency, Vault discipline, and testing.

Why This Matters

Configuration drift is the silent cause of "works on staging, broken in prod." Every manual SSH fix widens the gap between what your servers are and what you think they are. Ansible's value is not the first run — it is the hundredth run producing zero changes on a healthy fleet. If your playbooks cannot promise that, they are documentation with side effects, not automation.

Core Concepts

Idempotency Is the Whole Point

Every task should be safe to run repeatedly. Prefer modules over shell commands — a module knows the desired state; a shell command just runs. When you must use command or shell, guard it:

- name: Initialise the database only once
  ansible.builtin.command: /opt/app/bin/init-db
  args:
    creates: /var/lib/app/.initialised

If a re-run reports changed on tasks that should be stable, that is a bug report about your playbook, not noise to ignore.

Structure: Roles, Not Mega-Playbooks

Keep the layout Ansible itself recommends:

site.yml
inventories/
  production/hosts.ini
  staging/hosts.ini
roles/
  common/
  webserver/
  database/
group_vars/
host_vars/

Roles are the unit of reuse. A role that needs more than a screen of vars to explain itself is doing too much — split it. Pin role and collection versions in requirements.yml so a build six months from now resolves the same code.

Variables Have a Precedence Order — Use It Deliberately

Ansible has more than twenty variable precedence levels. The practical rule: defaults in the role (defaults/main.yml) for anything a consumer may override, real values in group_vars, secrets nowhere in plain text. When a value surprises you, a debug: var= task beats guessing.

Vault for Every Secret, No Exceptions

ansible-vault create group_vars/production/vault.yml
ansible-playbook site.yml --ask-vault-pass

Reference vaulted values through a plain indirection (db_password: "{{ vault_db_password }}") so playbooks stay readable and greppable. Rotate the vault password like any other credential, and never let an unencrypted secret touch git — one leak lives in history forever.

Handlers, Tags, and Check Mode

  • Handlers restart services only when a config actually changed — not on every run.
  • Tags let you run the risky slice of a playbook (--tags deploy) without the whole fleet update.
  • Check mode (--check --diff) is your pre-flight: run it in CI on every pull request so a bad template fails review, not production.
  • Decision Framework

    SituationReach for
    One-off fix on a handful of hostsAd-hoc commands, then codify it if it recurs
    Repeatable server configurationRoles + inventories per environment
    Secrets in playbooksAnsible Vault (or an external secret store lookup)
    Multi-team, scheduled, audited automationAWX / Ansible Automation Platform on top of the same content
    App deployment with complex orchestrationAnsible for the host layer; a dedicated CD tool for the app layer

    Implementation Checklist

  • [ ] Playbooks and roles in git, with requirements.yml pinned
  • [ ] Every playbook passes --check --diff cleanly against staging
  • [ ] Re-running a playbook on a healthy host reports no unexpected changes
  • [ ] All secrets in Vault or an external store — grep the repo for passwords to prove it
  • [ ] Handlers used for service restarts; no unconditional state: restarted
  • [ ] ansible-lint clean in CI
  • [ ] Molecule (or an equivalent) test for any role other teams depend on
  • Trade-offs

    Ansible is agentless and YAML-driven, which makes it approachable — and makes very large or highly dynamic fleets slower than agent-based tools. Push-style execution means a host that is offline during a run stays drifted until the next one. YAML's simplicity is also a ceiling: when playbooks grow loops inside loops inside conditionals, the logic belongs in a filter plugin or a different tool, not in more Jinja.

    When Not to Use Ansible

  • Immutable infrastructure shops: if you bake AMIs or container images and replace rather than patch, an image pipeline replaces most configuration management.
  • Pure Kubernetes estates: cluster state belongs in GitOps controllers; Ansible still helps for nodes and edge hosts, not for workloads.
  • Sub-minute convergence requirements: Ansible runs are batch operations, not a control loop.
  • References

    Here are valuable resources for mastering Ansible:

  • Ansible Documentation - Official Ansible documentation
  • Ansible Best Practices - Official best practices guide
  • Ansible Galaxy - Repository for Ansible roles
  • Ansible for DevOps - Jeff Geerling's comprehensive guide
  • Ansible Up & Running - O'Reilly's Ansible guide
  • Ansible Tower Documentation - Enterprise automation framework
  • Ansible Security Guide - Securing Ansible playbooks
  • Testing Ansible - Testing strategies
  • Ansible Collections - Using Ansible collections
  • AWX Project - Open source automation controller
  • These resources provide comprehensive information about Ansible configuration management.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.