Configuration Management (Ansible)
After this chapter you can
- Write an idempotent role and prove a second run changes nothing
Why this comes after Terraform#
In Infrastructure as Code, Terraform built the physical (virtual) hardware for us. We now have blank Linux servers sitting in the AWS Cloud. But a blank server is useless. We need to install Docker, configure Kubernetes, download security patches, and start services.
Doing this manually across 50 servers would take days. Ansible is the robot that logs into all 50 servers simultaneously and configures them in minutes. This is called Configuration Management.
In the capstone, Ansible turns the bare EC2 instance into the Jenkins host, through nine roles.
Level 1 — Beginner#
What is Ansible?#
Imagine you are the manager of a massive hotel with 500 rooms. You want to place a chocolate on the pillow of every bed.
- The Old Way: You walk to Room 1, unlock the door, place the chocolate, lock the door, and walk to Room 2. This takes 10 hours.
- The Ansible Way: You have a master radio. You broadcast a single message: "All housekeeping staff, go to your assigned room and put a chocolate on the pillow." It is done in 5 minutes.
Ansible is the master radio. The servers are the hotel rooms.
ASCII Diagram: The Ansible Workflow#
[ Your Laptop ]
| (Reads site.yml Playbook)
|
+---(SSH)---> [ EC2 Server 1 ] (Installs Docker)
+---(SSH)---> [ EC2 Server 2 ] (Installs Docker)
+---(SSH)---> [ EC2 Server 3 ] (Installs Docker)Notice that there is no "Ansible Agent" installed on the servers. Ansible just uses normal SSH, exactly as a human would.
Level 2 — Intermediate#
How it Works Internally (The Terminology)#
To use Ansible, you need to understand its language:
- Inventory: A list of IP addresses. Ansible needs to know who it is talking to.
- Tasks: A single action (e.g., "Install Docker" or "Start the firewall").
- Roles: A folder that groups many tasks together. (e.g., The "baseline" role contains 20 tasks to secure a new Linux server).
- Playbooks: The master script that maps Roles to the Inventory. (e.g., "Run the baseline role on all servers").
Roles — the unit of reuse#
A role is a directory with a fixed layout. Ansible loads the files by name, so you never write paths — putting a file in the right directory is the wiring:
roles/baseline/
tasks/main.yml what to do — the entry point
handlers/main.yml things triggered by `notify` (restart nginx, reload sshd)
defaults/main.yml variables the caller is expected to override
vars/main.yml variables the caller should not override
templates/ Jinja2 templates rendered onto the host
files/ files copied verbatim
meta/main.yml dependencies on other rolesUsing it is then one line:
- hosts: kubernetes_nodes
become: true
roles:
- role: baseline
- role: docker
vars:
docker_version: "24.0.7"defaults/ versus vars/ is the part that trips people up. Both define
variables; they differ in precedence. defaults sits near the bottom of
Ansible's precedence order, so anything — an inventory group, the playbook, a
--extra-vars flag — overrides it. vars sits near the top and is almost
impossible to override. The rule: every variable a caller might reasonably
change goes in defaults. Putting it in vars produces a role that cannot be
reused, which defeats the point of writing one.
When a role is worth it. A role is not free — it is seven directories and an indirection between the playbook and the work.
| Tasks in a playbook | A role | |
|---|---|---|
| Reused across playbooks | No | Yes |
| Ships with templates and handlers | Awkwardly | Naturally |
| Right for | A few steps, used once | Anything you will run on a second host group |
Write tasks inline first. Extract a role when a second playbook needs the same steps, or when the task list grows handlers and templates of its own. A role per five-line task list adds ceremony and hides the work.
For roles other people maintain, use Ansible Galaxy — and pin the version in
requirements.yml, for exactly the reason you pin a Terraform module:
roles:
- name: geerlingguy.docker
version: 7.0.1Practise: Automated Jenkins Server & Toolchain Provisioning composes roles into the capstone's build host, from a bare instance.
What Existed Before? (Chef and Puppet)#
Before Ansible, companies used Chef and Puppet. Why aren't they enough? They require you to install a background program (an Agent) on every single server before they can configure it. How do you install the agent? You have to do it manually! Ansible is Agentless, making it vastly superior for bootstrapping raw AWS EC2 instances.
Idempotency#
Like Terraform, Ansible is declarative. If you run a task that says "Ensure Docker is installed", and Docker is already installed, Ansible returns a green ok status and does absolutely nothing. It does not reinstall Docker.
Practise: Ansible Roles, Variables & Idempotency makes you prove the second run changes nothing.
Level 3 — Advanced#
Analyzing the Actual Code (Line-by-Line Breakdown)#
Let's look at how we build our entire Kubernetes cluster using Ansible.
1. The Dynamic Inventory#
In AWS, IP addresses change constantly. We can't hardcode IP addresses into a text file. Instead, we use 03-Ansible/inventories/aws_ec2.yml.
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
filters:
instance-state-name: running
"tag:Project": ivolve
keyed_groups:
# Role=control-plane -> group "control_plane"
- key: tags.Role
prefix: ""
separator: ""
- key: tags.Environment
prefix: env
separator: "_"
hostnames:
- private-ip-addressLine-by-line breakdown:
plugin: amazon.aws.aws_ec2— the fully-qualified collection name. The short formaws_ec2still works but is deprecated; using the FQCN is what stops a future Ansible release breaking your inventory silently.filters— Ansible asks AWS for every running instance taggedProject=ivolve. Terminated instances are excluded, so a node the ASG has replaced disappears from the inventory automatically.keyed_groupswith an empty prefix and separator turns the tagRole=control-planeinto a group literally namedcontrol_plane. That is why the playbooks can sayhosts: control_planewith no static file anywhere.hostnames: private-ip-address— the nodes have no public IP. They are reached through the bastion, via aProxyCommandbuilt further down the file.
This is the single most common Phase 3 failure. If
ansible-inventory --graphprints nothing, the EC2 tags do not match this filter. It looks like an Ansible bug and it is a tagging problem.
2. The Master Playbook#
Look at 03-Ansible/playbooks/site.yml — note that it contains no
tasks at all:
- import_playbook: 00-baseline.yml
tags: [baseline]
- import_playbook: 10-kubernetes-cluster.yml
tags: [kubernetes, cluster]
- import_playbook: 20-cluster-addons.yml
tags: [addons, ingress]
- import_playbook: 30-cicd-stack.yml
tags: [cicd, jenkins]
- import_playbook: 40-monitoring.yml
tags: [monitoring, observability]
- import_playbook: 50-gitops.yml
tags: [gitops, argocd]Line-by-line breakdown:
import_playbookcomposes the build from ordered stages rather than one 1,000-line file. The ordering is not cosmetic: the cluster must exist before the add-ons that live inside it, and ArgoCD cannot be installed before there is a cluster to install it into.tagsmake each stage independently runnable —ansible-playbook playbooks/site.yml --tags monitoringre-runs only the observability stage. When you are iterating on one role, this is the difference between a 40-second loop and a 25-minute one.
3. Real idempotency — a guard, not error suppression#
kubeadm init cannot run twice. Run it on a node that is already a control
plane and it fails. So how would a self-managed playbook be safe to re-run?
(The capstone uses EKS, so its Ansible provisions the Jenkins host instead —
but the idempotency pattern below is identical.)
A control-plane role would look like this:
- name: Check whether this node is already part of a cluster
ansible.builtin.stat:
path: /etc/kubernetes/admin.conf
register: kubeadm_admin_conf
- name: Determine the bootstrap node
ansible.builtin.set_fact:
is_bootstrap_node: "{{ inventory_hostname == groups['control_plane'][0] }}"
- name: Initialise the cluster
ansible.builtin.command:
cmd: kubeadm init --config /root/kubeadm-config.yaml --upload-certs
register: kubeadm_init
when:
- is_bootstrap_node
- not kubeadm_admin_conf.stat.exists
changed_when: kubeadm_init.rc == 0Line-by-line breakdown:
stat+when: not ...stat.exists— check foradmin.conf, the file that only exists after a successful init, and skip the task if it is there. The command is never attempted a second time.is_bootstrap_node— only the first control plane node runsinit; the othersjoin. Get this wrong and you get three separate one-node clusters that each believe they are in charge.changed_when— tells Ansible when to report changed rather than ok, so the run summary is truthful.
Why a guard rather than
failed_whenpattern-matching on the error text? Suppressing an error by matching a substring means you also suppress other failures that happen to contain that substring, and it breaks the moment upstream reword the message. Checking a precondition is deterministic. A task that is skipped is idempotent; a task that fails and is ignored is not.
Practise: Ansible Architecture, Configuration & Automated Inventory builds this inventory against real hosts — ones nobody typed into a file.
Level 4 — Enterprise#
Enterprise Patterns: Ansible Vault#
In an enterprise, you never store the database password in plaintext in GitHub. How does Ansible know the password to configure the RDS database? We use Ansible Vault.
Look at 03-Ansible/group_vars/vault.yml:
$ANSIBLE_VAULT;1.1;AES256
66316233383063386638333230626330366635396561333734616238653264663564613264353463This file is encrypted using AES256.
When the CI/CD pipeline runs ansible-playbook, we pass it a hidden decryption key. Ansible decrypts the file purely in memory, uses the password to connect to the database, and immediately flushes it from memory. The password never touches the hard drive in plaintext.
Immutable Infrastructure vs. Configuration Management#
In modern Platform Engineering (like Netflix), they rarely use Ansible to configure running production servers.
- Why? If a server has been running for 3 years, it has accumulated random files and logs. It is a "Snowflake".
- The Solution: Immutable Infrastructure. Instead of running Ansible against a live AWS server, they run Ansible against a temporary server using HashiCorp Packer. Packer saves the fully configured server as an Amazon Machine Image (AMI). Terraform then deploys 100 perfect clones of that AMI. If a server breaks, you don't fix it with Ansible; you delete it and let Terraform deploy a fresh clone.
When it breaks#
Symptom → evidence → hypothesis → test → fix. Ansible failures are nearly always one of three things: it cannot reach the host, it cannot become root, or the task is not actually idempotent.
UNREACHABLE#
Symptom. Failed to connect to the host via ssh, before any task runs.
Evidence. Ask the smallest possible question, with the verbosity up so you can see the exact SSH command being attempted:
ansible all -m ping -vvvHypothesis. This is an SSH problem, not an Ansible one. Usually the wrong
ansible_user, the wrong key, a host key that changed because the instance was
rebuilt, or a security group that never allowed 22 from where you are.
Test. Run the SSH command that -vvv printed, by hand. If it fails the same
way, Ansible was never involved.
Fix. Whichever the test found. Reach for host_key_checking = False only
knowing what it turns off — reasonable for throwaway lab hosts, and in production
it is accepting unauthenticated hosts.
Missing sudo password#
Symptom. The connection works, ping succeeds, and the first privileged task
fails.
Evidence. Run the play once with --ask-become-pass. If it then succeeds,
you have isolated the problem to privilege escalation.
Hypothesis. The remote user can log in but cannot escalate without a password, and Ansible has not been given one.
Test. On the host, sudo -n true exits non-zero when a password is required.
Fix. Give the automation user passwordless sudo on the hosts it manages, or supply the password from a vaulted variable. Never put it in the inventory in plain text — that file is in Git.
A task reports changed on every run#
Symptom. The second run is not green. Nothing is different, and Ansible says it changed things anyway.
Evidence. Run twice, read the recap, then look at which module the noisy task uses.
Hypothesis. command and shell cannot know whether the system already
matched, so they report changed every time. The other common cause is two tasks
fighting — a template writing a file and a lineinfile editing the same file
afterwards.
Test. --check --diff shows what Ansible believes it would alter.
Fix. Make the task describe a state rather than an action. Prefer a real
module; where you genuinely need a command, guard it with creates:, removes:
or an explicit changed_when:. Idempotency is not a nicety — it is what lets you
run a playbook against production without reading it line by line first.
The handler never ran#
Symptom. Configuration was written, the service was not restarted, and the play reported success.
Evidence. The notifying task reported ok, not changed.
Hypothesis. Handlers fire only when a notifying task actually changes something, and they run at the end of the play rather than at the point of notification. A task that fails after the notification also skips them.
Test. Change the file by hand, re-run, and watch the handler fire.
Fix. Usually nothing — this is correct behaviour, and it is why a second run
is quiet. When handlers must run despite a later failure, --force-handlers.
When a restart must happen at that point rather than at the end,
meta: flush_handlers.
Interview Questions#
Beginner#
Q: What is the difference between Terraform and Ansible? A: Terraform provisions the hardware (creates the AWS EC2 server). Ansible manages the configuration (installs Docker and Kubernetes onto that server).
Intermediate#
Q: How does Ansible connect to Linux servers? Do I need to install an Ansible Agent? A: No agent is required. Ansible connects natively via SSH (Port 22) using standard SSH key pairs.
Senior#
Q: Explain how Ansible Handlers work and why they are useful.
A: A Handler is a special task that only runs if notified by another task. For example, if Task A modifies the nginx.conf file, it notifies the Restart Nginx handler. If you run the playbook again, and nginx.conf does NOT change, the handler is not notified, and Nginx is not unnecessarily restarted. This is critical for preventing production downtime during configuration runs.
Principal/Architect#
Q: In a highly scalable auto-scaling environment, running ansible-playbook manually is an anti-pattern. How do you integrate configuration management into an ASG (Auto Scaling Group) lifecycle?
A: You integrate it at the image level or the boot level. Ideally, you use Packer to bake the Ansible configuration into a golden AMI, so instances boot ready to serve instead of configuring themselves first. If dynamic runtime configuration is strictly required, you use cloud-init (User Data) in the EC2 Launch Template to trigger an Ansible ansible-pull command. The instance reaches out to a Git repository on boot, downloads its own configuration, and configures itself before attaching to the Load Balancer, removing the need for a central Ansible push server.
Contents | Managed Databases (Amazon RDS) |
Practise it
Check yourself
6 questions from this chapter. Try answering before you look.
- What does idempotency mean in Ansible, and how do you prove it?
- When should a variable go in `defaults/` rather than `vars/`?
- What is the difference between Terraform and Ansible?
- How does Ansible connect to Linux servers? Do I need to install an Ansible Agent?
Recommended free courses
All coursesAnother way to learn this — external, free, and not affiliated with EgyKode.