Ansible remains my default for configuration management, not because it's the newest tool, but because it solves the messy middle between provisioning and running workloads. Terraform can spin up the infrastructure, Kubernetes can schedule containers, but someone still has to harden the OS, install agents, patch packages, and enforce baseline configuration across hundreds of otherwise identical hosts. Over the last six years managing fleets ranging from 40 to over 800 VMs across on-prem and AWS, I've seen Ansible playbooks go from a single 900-line YAML file that everyone was afraid to touch to a set of well-factored roles and dynamic inventories that new engineers could extend on day one. That transition didn't happen by following the docs verbatim; it happened by learning where Ansible's simplicity hides complexity, especially around variable precedence, inventory merging, and idempotency.
Decomposing Playbooks Into Composable, Idempotent Task Flows
A playbook that does everything in one file will work once. It will fail you on the second run. In my experience, the most reliable pattern is to treat playbooks as thin orchestration layers and delegate the actual work to imported task files or roles. A top-level site.yml should describe *what* runs where, not *how* it runs. This keeps your change blast radius small and makes --tags and --limit genuinely useful in production.
I've found that blocks with rescue and always are underused by intermediate teams. They are not just error handling; they are how you make operations atomic. If you are deploying a new Nginx config and the syntax check fails, you want to abort before you ever reload the service. Wrapping that sequence in a block means you don't leave a host in a half-configured state. Similarly, use check_mode and diff wherever possible during development; an idempotent task should report changed=0 on the second run without side effects.
Pattern: Entry Playbook with Conditional Imports
Rather than a monolithic play for webservers, I split by function and import conditionally. This example shows a site playbook that imports hardening, docker, and app deploy tasks based on group membership and variables. The when clauses are evaluated after fact gathering, so you avoid running irrelevant tasks entirely.
- name: Configure web tier
hosts: web
become: true
gather_facts: true
vars:
required_packages:
- fail2ban
- unattended-upgrades
tasks:
- name: Apply OS hardening
ansible.builtin.import_tasks: tasks/hardening.yml
tags: [hardening, base]
- name: Install and configure Docker
ansible.builtin.import_tasks: tasks/docker.yml
when: enable_docker | default(false)
tags: [docker]
handlers:
- name: Restart sshd
ansible.builtin.service:
name: sshd
state: restarted
- name: Deploy application stack
hosts: app
serial: 25%
tasks:
- ansible.builtin.import_role:
name: app_deploy
tags: [deploy]
Notice the use of import_role versus import_tasks. import_role is static and evaluated at playbook parse time, which means Ansible can expose its tags and variables for --list-tags. include_role is dynamic and conditional on runtime facts, but it hides complexity. I default to import_* for predictability and only use include_* when I need loops or host-specific conditions. That choice alone has cut our debugging time for failed runs by half.
Enforcing Idempotency at the Task Level
The second most common source of drift I've seen is shell and command modules without creates, removes, or changed_when. If you must use shell, always define when a task has actually changed something. For package installs, use the native apt/yum/dnf modules. For templated configs, the template module already handles idempotency via checksums, but be explicit about validate. For example, validating an Nginx template with nginx -t before overwriting the live file prevents a bad push from taking down the entire tier.
- name: Deploy Nginx vhost config
ansible.builtin.template:
src: vhost.conf.j2
dest: /etc/nginx/sites-available/app.conf
owner: root
group: root
mode: '0644'
validate: /usr/sbin/nginx -t -c %s
notify: Reload nginx
- name: Ensure Nginx is enabled and running
ansible.builtin.service:
name: nginx
state: started
enabled: true
Building Roles That Survive Team Growth and Environment Sprawl
A role is not just a folder structure; it's a contract for how your team shares automation. The default ansible-galaxy init scaffold is a good start, but production roles need stricter boundaries. In our organization, every role must be runnable in isolation with molecule, have documented required variables, and expose no leaky defaults that silently override group_vars. When roles bleed variables into global scope, you end up with precedence bugs that only appear in production.
I've moved almost entirely to the pattern where defaults/main.yml contains only safe, low-impact defaults, and vars/main.yml is rarely used. If a variable must not be overridden by inventory, it belongs in vars/. Everything environment-specific lives in group_vars or host_vars, not inside the role. This makes roles portable across staging, prod, and local Vagrant testing without forks.
Role Layout I Use in Production
This structure has held up for teams of 5-10 engineers managing 20+ roles in a single monorepo:
roles/
docker/
defaults/main.yml # version, daemon.json defaults
tasks/main.yml # install, configure, service
tasks/install.yml # OS-specific install logic
handlers/main.yml # restart docker
templates/daemon.json.j2
vars/Debian.yml # apt-specific vars
vars/RedHat.yml # yum-specific vars
molecule/default/converge.yml
meta/main.yml # dependencies, supported platforms
Inside tasks/main.yml, I include OS-specific vars dynamically and keep tasks small. This keeps the role idempotent on both Ubuntu 22.04 and RHEL 9 without duplicating logic. Dependencies in meta/main.yml should be used sparingly; I prefer explicit role composition in the playbook rather than hidden meta dependencies that pull in half your codebase.
For teams coming from Terraform, the mental model is similar to what I described in Terraform Modules: Design Patterns, Versioning and Registry Publishing - keep the interface narrow, version your roles with tags or Ansible Galaxy, and treat breaking variable changes as major versions. We pin roles in requirements.yml with a commit SHA for production and allow floating tags only in development.
Inventory Management Beyond Static Host Files
Static inventory files work until you autoscale. The moment you have an Auto Scaling Group or a set of ephemeral dev VMs, a hand-maintained hosts.ini becomes a liability. I have seen outages caused by deploying to a stale inventory that still contained terminated instances. The fix is to move to dynamic inventory plugins and treat inventory as generated data, not source code.
Ansible ships with inventory plugins for AWS EC2, Azure RM, GCP, OpenStack, and others. They query the cloud API at runtime and build groups based on tags, regions, or other metadata. You get automatic group creation like tag_Role_web and tag_Environment_prod without manual updates. Combined with constructed groups, you can build very expressive targeting: all hosts in us-east-1 that have the tag patch_group=canary.
Configuring the AWS EC2 Inventory Plugin
This aws_ec2.yml file lives in my inventory/ directory and is used with ansible-inventory -i inventory/aws_ec2.yml --graph to verify grouping before any run. The key is caching; without cache the plugin will call DescribeInstances on every playbook invocation, which throttles and slows execution.
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
- us-west-2
filters:
instance-state-name: running
tag:ManagedBy: ansible
keyed_groups:
- key: tags.Role
prefix: role
separator: ""
- key: tags.Environment
prefix: env
separator: "_"
- key: placement.region
prefix: region
compose:
ansible_host: public_dns_name
ansible_user: "'ubuntu'"
hostnames:
- tag:Name
- private-ip-address
cache: true
cache_plugin: jsonfile
cache_timeout: 300
cache_connection: /tmp/aws_ec2_cache
Even with dynamic inventory, I keep a static inventory directory for what cannot be discovered: group_vars, host_vars, and constructed inventories. A typical layout is inventory/prod/ with aws_ec2.yml, hosts (for bastions or on-prem nodes that aren't in AWS), and group_vars/env_prod.yml. This hybrid approach gives you discovery where it matters and explicitness where you need control.
For understanding how this scales, the comparison below reflects what I've observed running these approaches in parallel across different environments.
| Inventory Approach | Source of Truth | Update Latency | Ideal Use Case |
|---|---|---|---|
| Static INI/YAML File | Version-controlled file | Manual commit required | Small static fleets, bastions, network devices |
| Dynamic Plugin (aws_ec2) | Cloud API (tags, regions) | ~5 min with cache | Autoscaled workloads, ephemeral dev/test |
| Constructed Inventory | Derived from dynamic groups | Immediate at runtime | Building logical groups (canary, region-role) |
| Inventory From Terraform | terraform output / state | On apply | Tightly coupled provisioning + config workflows |
If you are already managing state with Terraform, you can also generate inventory from terraform output using the terraform-inventory script or by templating a hosts file. I cover the trade-offs of that coupling in Terraform State Management: Remote Backends, Locking and State Migration, but generally I prefer letting Ansible discover via the cloud plugin rather than creating a hard dependency on Terraform state files for day-two operations.
Handling Secrets, Variables, and Environment-Specific Configuration Without Sprawl
Ansible's variable precedence has 22 levels. That is not a feature; it's a hazard. In practice, you should use only four places: defaults/ for role defaults, group_vars/all.yml for global constants, group_vars/env_*.yml for per-environment values, and host_vars/ for true host-specific overrides. Vault-encrypted files for secrets, and nothing else. If you find yourself setting vars in playbooks, tasks, or --extra-vars for anything other than one-off debugging, your precedence is already too complex to reason about.
For secrets, ansible-vault is adequate for teams that don't yet have HashiCorp Vault or AWS Secrets Manager. The key is to vault-encrypt only the secret file, not the entire group_vars file, and to keep the vault password out of the repo. We use a vault password script that fetches from 1Password Connect in CI and from pass locally for developers. Each environment has its own vault file: group_vars/env_prod/vault.yml and group_vars/env_staging/vault.yml, both encrypted with different passwords. This limits blast radius if a password leaks.
Variable Layering That Remains Debuggable
Here is the hierarchy I enforce via code review. Variables defined higher up win, but we intentionally restrict ourselves to the lowest-precedence locations possible so overrides are predictable.
1. Role defaults (lowest, always overrideable). 2. group_vars/all.yml (global NTP, DNS, CA bundle). 3. group_vars/env_prod.yml (prod-specific domain, TLS settings). 4. host_vars/db01.yml (only for Snowflake hosts). 5. vault.yml (decrypted last, highest among our allowed set). I explicitly ban vars/, set_fact in roles for configuration, and --extra-vars in CI except for image tags.
To keep this auditable, run ansible-inventory --host hostname --list and ansible-playbook --check --diff before any production change. The diff output is invaluable for catching templated config drift, especially for files like sshd_config or sysctl.conf where a single wrong value can lock you out. For more complex policy validation beyond diff, we now run the rendered configs through Checkov, an approach I outlined in Infrastructure Testing: Terratest, Checkov and Policy-as-Code Validation.
Orchestrating Zero-Downtime Rolling Updates With Handlers and Serial Strategies
Configuration management is not useful if applying it causes an outage. Ansible's combination of serial, max_fail_percentage, and handlers is how you get safe rolling deployments without a separate orchestrator. A common mistake is to restart a service with a task instead of a handler; handlers coalesce multiple notifications into a single restart at the end of the play, which avoids flapping a service five times if five configs changed.
For web tiers behind a load balancer, the pattern is: disable in load balancer, update, validate health, re-enable. Ansible can do this directly with delegate_to against your load balancer or via cloud modules. The serial keyword controls how many hosts are updated at once. I almost always use serial: "25%" or serial: 2 rather than serial: 1 for large fleets to balance speed and safety. Pair it with max_fail_percentage: 25 so the play aborts if a quarter of the hosts fail, rather than blindly continuing across the whole fleet.
Rolling Update Play With Pre and Post Tasks
This pattern handles draining, deployment, and validation. It assumes your load balancer is NGINX or HAProxy managed by Ansible, but the same idea works with AWS ELB deregistration using the elb_target module.
- name: Rolling update of app servers
hosts: app
serial: "25%"
max_fail_percentage: 25
become: true
pre_tasks:
- name: Disable host in load balancer
ansible.builtin.command: /usr/local/bin/disable-pool-member {{ inventory_hostname }}
delegate_to: "{{ groups['lb'][0] }}"
changed_when: false
tasks:
- name: Deploy application artifact
ansible.builtin.unarchive:
src: app-{{ app_version }}.tar.gz
dest: /opt/app
owner: app
group: app
notify: Restart app
post_tasks:
- name: Wait for app to become healthy
ansible.builtin.uri:
url: http://{{ ansible_host }}:8080/healthz
status_code: 200
register: health
until: health.status == 200
retries: 10
delay: 3
- name: Enable host in load balancer
ansible.builtin.command: /usr/local/bin/enable-pool-member {{ inventory_hostname }}
delegate_to: "{{ groups['lb'][0] }}"
changed_when: false
handlers:
- name: Restart app
ansible.builtin.systemd:
name: app
state: restarted
daemon_reload: true
If you are running containers, delegate the container lifecycle to Docker or Podman modules instead of shell. The Docker Documentation is the definitive reference for daemon.json and restart policies, and the community.docker collection mirrors those options cleanly. I've found the docker_container module with restart_policy: unless-stopped and healthcheck support to be far more idempotent than manual docker run commands wrapped in shell.
Integrating Ansible Into Terraform and GitOps-Driven Pipelines
Ansible does not provision infrastructure; it configures it. The cleanest boundary I've used is Terraform provisions, Ansible configures. Terraform creates the VPC, instances, and load balancers and outputs instance IDs or IPs. Ansible then discovers those hosts via inventory plugin and converges them. This avoids the anti-pattern of calling ansible-playbook from a Terraform provisioner, which couples state and configuration and makes both harder to rerun. The Terraform Documentation itself now recommends against provisioners for anything beyond trivial bootstrapping.
In CI, Ansible should run in check mode on every pull request and in full mode only on merge to main. We use a GitHub Actions job that runs ansible-lint, molecule test, and ansible-playbook --check --diff against staging inventory. That job must be green before merge. On merge, a second workflow runs ansible-playbook against staging, then waits for manual approval to promote the same artifact and playbook to production. This mirrors GitOps principles where Git is the source of truth, even though Ansible is not Kubernetes-native. For teams already moving to GitOps with ArgoCD, a similar flow is described in GitOps with ArgoCD and Flux: Declarative Kubernetes Deployment - the tool differs, but the principle of declarative, reviewed, auditable changes is identical.
Speed matters at scale. Fact gathering via gather_facts is often the slowest part of a run. If you don't need facts, disable them. If you do, cache them. Enable fact caching in ansible.cfg with fact_caching = jsonfile and fact_caching_timeout = 86400. Mitogen for Ansible or the newer pipelining + ControlPersist SSH optimizations also cut runtime significantly. On a 300-host fleet, we dropped a full site run from 14 minutes to under 4 minutes by enabling pipelining, disabling unnecessary fact gathering, and forking to 20 parallel processes (forks = 20). Test forks carefully - too high and you will throttle your cloud API or overwhelm your bastion.
Finally, log everything. Set callback_whitelist = profile_tasks, timer, and log_plays in ansible.cfg and ship those logs to your central system. When a playbook fails at 2 a.m., you want to know which task took longest and what changed on which host without re-running with -vvv.
Frequently Asked Questions
Should I use Ansible to provision cloud infrastructure or stick to Terraform?
Use each for what it does best. Terraform is declarative and stateful, ideal for creating VPCs, VMs, and managed services. Ansible is procedural and stateless, ideal for configuring the OS and applications on top of that infrastructure. In my experience, mixing them - Terraform provisioners that call Ansible - creates fragile state dependencies. Keep them separate: Terraform outputs inventory or tags, Ansible discovers and configures.
How do you manage variable precedence so it doesn't become unpredictable?
Restrict yourself to four locations: role defaults/main.yml, group_vars/all.yml, group_vars/env_*.yml, and host_vars/. Vault-encrypt a separate vault.yml per environment. Avoid setting variables in plays, tasks, or via --extra-vars except for temporary overrides. Run ansible-inventory --host <hostname> --list to inspect the merged variables before debugging a failed run.
When should I choose a dynamic inventory plugin over a static hosts file?
Choose dynamic inventory when hosts are ephemeral, autoscaled, or frequently replaced, such as EC2 Auto Scaling Groups or development environments. Keep a static inventory for long-lived, non-discoverable hosts like on-prem bastions, network appliances, or bare-metal servers that lack cloud tags. Most mature setups use a hybrid: dynamic plugin for cloud workloads and a small static file for the rest, plus group_vars for shared configuration.
Can Ansible handle rolling updates without downtime?
Yes, using serial, max_fail_percentage, pre_tasks/post_tasks, and handlers. Set serial to a percentage like "25%" so only a quarter of the hosts update at once, drain each host from the load balancer in pre_tasks, apply changes, validate health with the uri module, and re-add in post_tasks. Handlers ensure services restart only once at the end, and max_fail_percentage aborts the run if too many hosts fail.