The first time I migrated a fleet of 40 servers from one log shipper to another, I did it by hand. SSH, edit, restart, verify, next box. Took a weekend, broke two servers, and the next week I did it again because I'd missed a config flag. The third time, I wrote a bash loop with ssh $host and a heredoc, and that's when I learned the lesson that pushes everyone to Ansible eventually: a for-loop over SSH is not automation. It's a faster way to make the same mistake on every machine at once.
Ansible is the tool you reach for when you're tired of "works on my machine" and tired of "I think I configured all 30 the same way." It's agentless, it speaks SSH (and WinRM), it's idempotent if you let it be, and it ships with thousands of modules that already know how to install packages, manage files, and restart services correctly. The thing it isn't is magic. You can still shoot yourself in the foot, and most people do, by writing plays that look fine in a one-off run and quietly diverge over time.
This is the article I wish I'd had the first time I tried to wrap a real fleet in Ansible and ended up with a roles directory that nobody understood.
What Ansible Actually Is (and What It Isn't)
Ansible is a config-management tool. You write declarative YAML ("this package should be installed, this file should contain this, this service should be running"), point it at an inventory of hosts, and it makes reality match the YAML. Underneath, it generates Python scripts, ships them to the target over SSH, executes them, and removes them. No daemon, no agent, no port to open beyond 22.
What it's not: a provisioning tool. Ansible can call AWS/GCP/Azure APIs via modules, but if you're spinning up ephemeral infrastructure regularly, Terraform is better at it. Ansible is also not an orchestration system like Kubernetes - it doesn't reconcile continuously, it runs once and exits. Think of it as the thing that takes a freshly provisioned box from "ssh works" to "running my app correctly" and keeps it there when you re-run.
| Tool | Agentless | Model | Best for | Weakness |
|---|---|---|---|---|
| Ansible | Yes (SSH/WinRM) | Push, imperative YAML | Multi-host config, ad-hoc ops | Slow at 1000+ hosts, YAML can get hairy |
| Puppet | No (daemon) | Pull, declarative DSL | Long-lived fleet, drift detection | DSL learning curve, master overhead |
| Chef | No (daemon) | Pull, Ruby DSL | Ruby shops, complex cookbooks | Heavy, Ruby-dependent |
| SaltStack | Both | Push/pull, event bus | Real-time orchestration | Two daemons, complex to operate |
| Terraform | Yes | Pure declarative | Cloud provisioning | Not for in-host config |
I keep Ansible in my toolkit because it's the one I can drop onto a new client's fleet in an afternoon, with no permission to install agents and no master to babysit. That's the tradeoff: simple to start, and you'll outgrow certain patterns as you scale.
Prerequisites
- A control machine with Python 3.10+. That's your laptop or a CI runner.
- Target hosts reachable over SSH with a non-root user that has passwordless
sudo. Ansible will refuse to do most useful things as root directly, and rightly so. - Python 3 on the targets. Ansible pushes Python scripts; if the target has no Python, the very first thing you do is bootstrap it (there's a
rawmodule for exactly this). - SSH key auth set up. Passwords over SSH work but you'll regret it the first time a play hangs waiting on a prompt that never comes.
- A reasonable text editor with YAML schema support. VS Code + the Ansible extension saves you from whitespace errors.
- An inventory of hosts you're allowed to touch. Don't point Ansible at production for the first time without
--checkuntil you trust your playbooks.
If you're on macOS, also install brew install gnu-tar. Ansible uses gtar for unarchive and the BSD tar that ships with macOS has subtle incompatibilities that bite you on Linux targets.
How Ansible Fits Together
Four concepts carry 90% of Ansible: inventory, modules, tasks, and plays. Everything else is sugar.
CodeCopy
┌─────────────┐ SSH/Python ┌──────────────────┐
│ Control │ ───────────────> │ Target host │
│ machine │ <─────────────── │ (Python script │
│ (ansible) │ stdout/stderr │ pushed & run) │
└──────┬──────┘ └──────────────────┘
│
│ reads
▼
┌─────────────┐ ┌─────────────┐ ┌─────────────────┐
│ Inventory │ │ Playbook │ │ Roles + vars │
│ (hosts.ini) │ │ (tasks yml) │ │ (reusable) │
└─────────────┘ └─────────────┘ └─────────────────┘
The inventory is a list of hosts grouped by purpose. The playbook is a list of plays; each play targets a group and runs a list of tasks. Each task calls a module with parameters. Modules do the actual work: apt, copy, template, systemd, user. The power is that modules are idempotent - apt: name=nginx state=present is a no-op if nginx is already installed, and the playbook reports "changed: 0" so you know nothing actually happened.
The mistake I see repeatedly: people write plays that look declarative but aren't. command: apt-get install -y nginx runs every time, reports "changed" every time, and hides whether anything actually changed. Use the module. Always.
Installation
Three honest paths.
pip (recommended for control machines): keeps Ansible isolated from system Python, easy to upgrade, easy to pin in a requirements file.
BashCopy
shell
python3 -m venv ~/.venvs/ansible
source ~/.venvs/ansible/bin/activate
pip install ansible
ansible --version
markdown
System package manager: convenient, but lags. Debian/Ubuntu ship Ansible versions 6-12 months behind upstream, which matters because module bugs get fixed fast upstream. apt install ansible, dnf install ansible, brew install ansible.
Containers: for CI you want a pinned, reproducible environment. The official image is decent.
BashCopy
shell
docker pull quay.io/ansible/creator-ee:latest
docker run --rm -v $(pwd):/work -w /work quay.io/ansible/creator-ee:latest ansible-playbook site.yml
markdown
I run Ansible from a venv on my laptop for ad-hoc work and from the container image in CI for anything that gates deploys. Same playbook, two execution contexts, identical results.
The Inventory: Where Plays Start Lying
The inventory is the single biggest source of "Ansible is broken" tickets. It's where drift creeps in first. Two formats are supported: INI and YAML. INI is simpler to read; YAML is more powerful for variable grouping. Pick one and stay with it.
iniCopy
ini
inventory/production.ini
[webservers]
web01.prod.example.com ansible_host=10.0.1.11
web02.prod.example.com ansible_host=10.0.1.12
web03.prod.example.com ansible_host=10.0.1.13
[dbservers]
db01.prod.example.com ansible_host=10.0.2.21 postgres_version=15
[loadbalancers]
lb01.prod.example.com
[production:children]
webservers
dbservers
loadbalancers
[production:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/prod_deploy
ansible_python_interpreter=/usr/bin/python3
plaintext
Three things to notice. First, ansible_host lets you decouple the logical name (web01.prod) from the actual address. When you migrate to a new VPC, you change the IP in one place and the playbooks don't change. Second, group vars and group children compose - production:vars applies to every host in webservers, dbservers, and loadbalancers. Third, ansible_python_interpreter matters: on modern distros /usr/bin/python may not exist, and Ansible's autodetection has historically been flaky. Pin it.
For anything bigger than a homelab, use a dynamic inventory. The AWS, GCP, and Azure plugins all query the cloud API at runtime, so your inventory is never stale. Here's the pattern I use for AWS:
YAMLCopy
yaml
inventory/aws_production.yml
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
- us-west-2 hostnames:
- private-ip-address filters: tag:Environment: production instance-state-name: running groups: webservers: "'web' in tags.Role" dbservers: "'db' in tags.Role" compose: ansible_user: "'deploy'"
plaintext
Run ansible-inventory -i inventory/aws_production.yml --graph and you should see your live fleet. If a box is missing, it's because the tag is wrong or the instance is stopped - and that's information you want before a deploy, not after.
Your First Playbook (That Doesn't Bite You Later)
Here's a real playbook I use to provision a fresh nginx webserver. It's small but it demonstrates the patterns that scale: a handler for service restart, a template for config, a notify chain so a config edit only restarts nginx when the config actually changes.
YAMLCopy
yaml
playbooks/webservers.yml
- name: Configure webservers hosts: webservers become: true vars: nginx_worker_processes: auto nginx_worker_connections: 4096
tasks:
name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
tags: installname: Ensure nginx config directory exists
ansible.builtin.file:
path: /etc/nginx/conf.d
state: directory
owner: root
group: root
mode: "0755"name: Render nginx main config
ansible.builtin.template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: "0644"
validate: nginx -t -c %s
notify: Reload nginx
tags: configname: Ensure nginx is enabled and running
ansible.builtin.systemd:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx ansible.builtin.systemd: name: nginx state: reloaded
plaintext
The template task uses validate: nginx -t -c %s. That %s is replaced with the temp path of the rendered file before it's copied. If your Jinja template has a syntax error, the play fails before nginx ever sees the broken config. This is the single best feature in the template module and almost nobody uses it. Add it to every config template that has a -t style validation command - sshd -t, nginx -t, haproxy -c, named-checkconf.
Run it:
BashCopy
shell
ansible-playbook -i inventory/production.ini playbooks/webservers.yml --check --diff
markdown
--check is a dry run; Ansible reports what it would change without changing it. --diff shows you the exact line-by-line diff of any templated file. Run with both flags the first time against any new host. If the diff looks wrong, you've caught a bug before it touched prod.
Idempotency: The Property That Saves Your Life
A playbook is idempotent if running it once produces the same result as running it a hundred times. Idempotency is what lets you run Ansible every hour to correct drift without rewriting every file on every host. The modules handle most of this for you - apt: state=present checks first, file: state=directory stats first - but you can break it.
The classic break is using command or shell modules for things that should use a real module. These modules always report changed: true because Ansible can't know whether the command's effect was idempotent. The fix is the creates/removes argument, which tells Ansible to skip the task if a file exists (or doesn't):
YAMLCopy
yaml
- name: Run database migration ansible.builtin.command: /usr/local/bin/migrate.sh args: creates: /var/lib/myapp/.migrations_applied
markdown
Better: have your migration script touch a sentinel file when it succeeds, or check the DB schema version first. Real idempotency means the playbook reports "changed: 0, unreachable: 0, failed: 0" on the second run, and that's what your monitoring should alert on. If changed is non-zero on a steady-state playbook, something is drifting, and you want to know about it before it becomes an outage.
Another break I see often: copy with a content that includes a timestamp. content: "Generated at {{ ansible_date_time.iso8601 }}" will report changed on every run because the content is different every time. Use templates only when the content genuinely depends on host variables, and never on time.
Roles: When Your Playbook Outgrows One File
Once a playbook crosses ~150 lines, split it into a role. Roles have a conventional directory layout that Ansible loads automatically:
CodeCopy
plaintext
roles/
└── nginx/
├── defaults/
│ └── main.yml # low-priority defaults, overridable
├── vars/
│ └── main.yml # high-priority internal vars
├── tasks/
│ └── main.yml # the task list
├── handlers/
│ └── main.yml # handlers notified by tasks
├── templates/
│ └── nginx.conf.j2
├── files/
│ └── (static files)
├── meta/
│ └── main.yml # role metadata + dependencies
└── README.md
plaintext
The defaults/main.yml vs vars/main.yml distinction trips up everyone. defaults are the lowest-priority variables in Ansible - anything overrides them, including inventory vars and even other defaults. They're the "if nobody tells me otherwise" values. vars are very high priority - only set_fact and explicit -e extra vars override them. Put user-tunable knobs in defaults; put things that should never be overridden (internal paths, module names) in vars.
To use a role from a playbook:
YAMLCopy
yaml
- name: Configure webservers
hosts: webservers
become: true
roles:
- role: nginx vars: nginx_worker_processes: 4
plaintext
For shared roles across projects, put them in a requirements.yml and install with ansible-galaxy:
YAMLCopy
yaml
requirements.yml
roles:
- name: nginx src: https://github.com/myorg/ansible-role-nginx version: v2.3.0
plaintext
BashCopy
shell
ansible-galaxy install -r requirements.yml -p roles/
plaintext
Pin versions. Tags, not branches. If you let version: main, the day someone force-pushes the upstream role, your next CI run breaks for no reason you can trace. Pinning is two minutes of pain now versus hours of debugging later.
Variables, Facts, and the Magic ofwhen
Every task can run conditionally. Every host has facts (system info gathered at the start of a run). Together these let you write plays that adapt to what they find.
YAMLCopy
yaml
name: Show OS family
ansible.builtin.debug:
msg: "This host is {{ ansible_os_family }} {{ ansible_distribution_version }}"name: Install EPEL on RedHat-family only
ansible.builtin.dnf:
name: epel-release
state: present
when: ansible_os_family == "RedHat"-
name: Use Python 3.11 on Ubuntu 22.04+
ansible.builtin.set_fact:
python_version: "3.11"
when:- ansible_distribution == "Ubuntu"
- ansible_distribution_version is version("22.04", ">=")
plaintext
Facts are gathered automatically at the start of each play. They cost a second or two per host; if you don't need them, gather_facts: false on the play will skip it and speed things up. For large fleets, set up fact caching so re-runs don't re-gather:
YAMLCopy
ini
ansible.cfg
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
fact_caching_timeout = 86400
plaintext
Now facts are gathered once per day per host. Across a 200-host fleet, this cuts playbook runtime by 30-60%. Worth it.
Loops are the other pattern you'll use constantly:
YAMLCopy
yaml
- name: Create app users
ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ item.groups | default(omit) }}"
shell: /bin/bash
loop:
- { name: alice, groups: "sudo,docker" }
- { name: bob, groups: "docker" }
- { name: carol }
markdown
default(omit) is a beautiful trick: if groups isn't set, the parameter is omitted entirely rather than set to empty string. omit is the difference between "create user with no groups" and "create user with default groups."
Ansible Vault: For the Secrets You Used to Commit in Plaintext
You will, at some point, be tempted to commit a vault_password or an API key into a vars file. Don't. Use Ansible Vault. Vault encrypts specific variables or whole files with AES-256, and Ansible decrypts them transparently at runtime when you supply the password.
BashCopy
shell
Encrypt a single variable
ansible-vault encrypt_string --vault-id prod@~/.vault_prod 'supersecret123' --name 'db_password'
Encrypt a whole file
ansible-vault encrypt group_vars/production/vault.yml
Edit an encrypted file in place
ansible-vault edit group_vars/production/vault.yml
plaintext
For anything beyond a homelab, use vault IDs with separate passwords per environment:
BashCopy
shell
Create a password file (chmod 600!)
echo 'my-prod-vault-password' > ~/.vault_prod
chmod 600 ~/.vault_prod
Encrypt with the prod vault ID
ansible-vault encrypt --vault-id prod@~/.vault_prod group_vars/production/vault.yml
Run plays with the prod vault ID
ansible-playbook --vault-id prod@~/.vault_prod site.yml
plaintext
The vault password file should live in a password manager (1Password, Bitwarden) or be fetched on demand. For CI, store the vault password in your CI provider's secret store and write it to a temp file at runtime:
YAMLCopy
yaml
.github/workflows/ansible.yml
- name: Decrypt and run env: VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_PROD }} run: | echo "$VAULT_PASSWORD" > /tmp/vault_pass chmod 600 /tmp/vault_pass ansible-playbook --vault-id prod@/tmp/vault_pass site.yml shred -u /tmp/vault_pass
markdown
The mistake I see constantly: devs put the vault password file in the same git repo as the encrypted secrets, "just for convenience." That defeats the entire purpose. The encrypted blob is safe to commit; the password is not. Treat them like they're two halves of a key - neither alone opens anything, but together they open everything.
Async Tasks and Long-Running Operations
Ansible blocks on each task by default. If you kick off a 30-minute database restore, your playbook is stuck for 30 minutes. For long-running tasks, use async:
YAMLCopy
yaml
name: Restore database snapshot (async)
ansible.builtin.command: pg_restore -d myapp /tmp/snapshot.dump
async: 3600 # max seconds to wait
poll: 30 # check every 30s
register: restore_jobname: Wait for restore to complete
ansible.builtin.async_status:
jid: "{{ restore_job.ansible_job_id }}"
register: job_result
until: job_result.finished
retries: 120
delay: 30
markdown
For fire-and-forget tasks (kick off a build, don't wait), set poll: 0 and the task returns immediately. Useful when you want to fan out a heavy operation across many hosts in parallel without blocking.
Production Considerations
Scaling: Ansible is slow at large fleets because it opens one SSH connection per host and serializes within serial batches. For 500+ hosts, set forks: 50 (or higher) in ansible.cfg, enable SSH multiplexing, and use pipelining: true to cut the per-task SSH overhead:
iniCopy
ini
ansible.cfg
[defaults]
forks = 50
pipelining = true
host_key_checking = false
timeout = 30
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o PreferredAuthentications=publickey
plaintext
Pipelining requires requiretty to be disabled in sudoers on targets (it is by default on modern distros). The combined effect: 2-3x speedup on playbooks with many small tasks.
Performance: Profile your plays. ANSIBLE_PROFILE=1 or the profile_tasks callback shows per-task timings:
iniCopy
ini
[defaults]
callback_enabled = profile_tasks
markdown
You'll be surprised which tasks are slow. Usually it's apt: update_cache: true running on every play; cache it once per day via a separate update_apt_cache play that runs first.
Security: Use become: true per-play, not globally. Never run as root over SSH directly. Use become_user to drop privileges for tasks that don't need root. Rotate the SSH deploy key quarterly. Restrict sudo for the deploy user to the specific commands Ansible needs (don't give full NOPASSWD: ALL unless you have to).
Monitoring: Send play results to your observability stack. The simplest pattern is a wrapper script that runs ansible-playbook, parses the JSON output (--tree or callback), and pushes a metric. If changed is unexpectedly high on a steady-state run, alert.
Logging: Log every play with --check first. Log the actual run with full output. Store both. When something breaks three days later, the playbook log is your forensic evidence of what changed.
Common Mistakes (and How to Spot Them)
Using command/shell instead of modules. Symptom: every task reports changed: true even when nothing changed. Fix: replace with the appropriate module (apt, file, systemd, user); use creates/removes if you genuinely need a shell command.
Forgetting become: true on tasks that need root. Symptom: "Permission denied" on the first privileged task. Fix: add become: true at the play level, or per-task. Don't run the entire play as root if you don't need to.
Hardcoding paths and IPs in tasks. Symptom: the playbook works on one host and fails on another. Fix: move values to defaults/main.yml, override per-environment in inventory.
Committing vault passwords. Symptom: a security audit finds your prod DB password in git history. Fix: rotate immediately, use vault IDs, store passwords in a password manager.
Not pinning role versions. Symptom: a CI run that worked yesterday fails today with no code change. Fix: pin version: in requirements.yml to a tag, never a branch.
Trusting changed without checking. Symptom: a steady-state playbook reports 15 changed every run. Fix: investigate. Either the task isn't idempotent (use the right module), or there's genuine drift (something else is editing the file).
Ignoring ansible_python_interpreter. Symptom: cryptic /usr/bin/python: not found errors on Ubuntu 20.04+. Fix: set ansible_python_interpreter=/usr/bin/python3 in inventory.
Troubleshooting, From Real Production
"SSH Error: ssh: connect to host X port 22: Connection refused". The host is up but sshd isn't running, or a firewall is blocking. From the control machine: ssh -v deploy@host to confirm. If ssh works manually but Ansible fails, check ansible_user and ansible_ssh_private_key_file in inventory - Ansible isn't using your interactive SSH config.
"MODULE FAILURE: See stdout/stderr for the actual error". Almost always a Python problem on the target. SSH in manually and run python3 -c "import json; print(json.dumps({'ok': True}))". If that fails, you need to install Python or fix the interpreter path.
"Failed to lock apt for exclusive operation". Another apt process (unattended-upgrades, a manual apt install) is running. Either wait, or set environment: DEBIAN_FRONTEND: noninteractive and retry with retries: 3 delay: 10 on the apt task. Long-term: disable unattended-upgrades on Ansible-managed hosts, or schedule them outside your playbook window.
"Timeout (12s) waiting for privilege escalation prompt". The deploy user has sudo configured to require a password. Either configure NOPASSWD for the specific commands, or pass -K and enter the sudo password at runtime (not suitable for CI).
"fatal: [host]: FAILED! => template error while templating string". A Jinja2 syntax error in your template. The error message usually points to the line. Common cause: {{ }} inside a YAML string that's also using {% %} blocks; check for missing quotes or unbalanced braces.
Testing with Molecule
A playbook that's never been tested is a hypothesis. Molecule is the standard test framework for Ansible roles: it spins up a container (or VM), runs your role, idempotency-checks it, runs your tests, and tears down.
YAMLCopy
yaml
roles/nginx/molecule/default/converge.yml
- name: Converge
hosts: all
roles:
- role: nginx
plaintext
YAMLCopy
yaml
roles/nginx/molecule/default/molecule.yml
driver:
name: docker
platforms:
- name: instance image: geerlingguy/docker-ubuntu2204-ansible pre_build_image: true command: /sbin/init privileged: true provisioner: name: ansible verifier: name: ansible
plaintext
YAMLCopy
yaml
roles/nginx/molecule/default/verify.yml
-
name: Verify
hosts: all
tasks:- name: Check nginx is listening ansible.builtin.command: curl -fsS http://localhost/ changed_when: false
- name: Assert nginx config is valid ansible.builtin.command: nginx -t changed_when: false
markdown
Run molecule test from the role directory. The full cycle (create, converge, idempotence, verify, destroy) takes a minute or two and catches the three most common bugs: syntax errors, idempotency breaks, and "works on Ubuntu but not Debian" issues.
CI/CD: Run Every Playbook Before Merge
Here's the GitHub Actions workflow I use to run Molecule tests on every PR and a full --check against staging on merge to main:
YAMLCopy
yaml
.github/workflows/ansible.yml
name: Ansible CI
on:
pull_request:
push:
branches: [main]
jobs:
molecule:
runs-on: ubuntu-latest
strategy:
matrix:
distro: [ubuntu2204, debian12]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5 with: python-version: "3.11"
- run: pip install ansible molecule molecule-docker
- run: molecule test env: MOLECULE_DISTRO: ${{ matrix.distro }}
staging-check:
if: github.ref == 'refs/heads/main'
needs: molecule
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5 with: python-version: "3.11"
- run: pip install -r requirements.txt
- name: Decrypt vault env: VAULT_PASSWORD: ${{ secrets.ANSIBLE_VAULT_STAGING }} run: echo "$VAULT_PASSWORD" > /tmp/vp && chmod 600 /tmp/vp
- name: Run playbook in check mode run: ansible-playbook --vault-id staging@/tmp/vp -i inventory/staging.yml site.yml --check --diff
- if: always() run: shred -u /tmp/vp || true
The matrix runs each role against multiple distros - the "works on Ubuntu but not Debian" bug is real and frequent. The staging-check runs in --check mode so it never accidentally applies, but it does surface "the staging fleet has drifted" before someone tries to apply on Monday morning.
Cost Considerations
Ansible itself is free (GPLv3). The cost is operational: control-machine compute, CI minutes, and your time. Open-source Ansible is fully featured; Ansible Automation Platform (AAP, formerly Ansible Tower) is Red Hat's commercial offering that adds a web UI, RBAC, job scheduling, and a REST API. AAP is ~$10k/year per 100 nodes at list price - only worth it if you have a team that needs RBAC and audit trails across environments.
For self-hosted alternatives to AAP: AWX is the open-source upstream of AAP, free, slightly rougher, and fine for small teams. Semaphore is a lighter web UI. I've shipped both; AWX wins on features, Semaphore wins on simplicity.
Cloud cost: the bigger lever is what Ansible does. If your playbooks provision ephemeral instances and forget to tear them down, that's the bill that hurts. Terraform for provisioning, Ansible for config, lifecycle hooks for teardown.
Real-World Use Cases
-
Fleet patching: a weekly playbook that runs
apt upgrade, reboots if needed (withrebootmodule +wait_for_connection), and reports which hosts patched successfully. Drift-correcting playbooks that run nightly catch boxes that fell out of compliance. - App deployment: trigger a deploy playbook from CI that pulls the new artifact, renders config, runs DB migrations, restarts the app with health-check waits, and rolls back if the health check fails.
- Security hardening: a baseline role that enforces SSH config, disables unused services, installs and configures auditd, and applies CIS benchmark recommendations. Run periodically to correct drift.
- Disaster recovery: a "rebuild from scratch" playbook that takes an empty host and brings it up to a fully configured service, ready to receive traffic. The playbook is also your documentation; if it's not in the playbook, it's not in the DR plan.
Conclusion
Ansible is the tool you reach for when you want to stop doing the same thing 30 times by hand. Its strength is that it's agentless, declarative, and idempotent; its weakness is that YAML is verbose and the temptation to write non-idempotent shell-in-disguise tasks is constant. The patterns that scale are the boring ones: use modules, split into roles, pin dependencies, test with Molecule, run in CI with --check --diff, encrypt secrets with vault, and alert on unexpected changed counts. Do those things and Ansible will keep your fleet honest. Skip them and you'll have a roles/ directory nobody understands by month six.
Originally published on Mango Developer.
Top comments (0)