Ansible
Configuration Management, Playbooks, and Agentless automation.
Ansible
Terraform builds the house (Server, VPC, DNS). Ansible furnishes the rooms (Installs Nginx, updates patches, creates users).
Ansible is a Configuration Management tool. It ensures that a group of servers matches a specific state.
Core Concepts
1. Agentless (Push Model)
Unlike Puppet or Chef, Ansible does not require an agent installed on the target server. It runs on your laptop (or CI server) and pushes commands over SSH.
2. Inventory
A simple text file listing the servers you want to manage.
[webservers]
192.168.1.50
192.168.1.51
[databases]
db-01.internal3. Playbooks (YAML)
The declarative instructions. "Ensure Nginx is installed."
- name: Configure Webservers
hosts: webservers
become: true # Run as sudo
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Start Nginx
service:
name: nginx
state: startedIdempotency
The most important word in Ansible.
- Imperative (Bash):
apt-get install nginx. If you run this twice, it might error or try to reinstall. - Declarative (Ansible):
state: present. Ansible checks if Nginx is there. If yes, do nothing. If no, install it.
The Golden Image Dilemma
In modern Cloud Engineering, we often prefer Immutable Infrastructure (Building a baked AMI with Packer containing all software) rather than patching live servers with Ansible.
Use Ansible when:
- You manage long-lived "Pet" servers (on-premise, legacy).
- You need to perform ad-hoc tasks (rotating SSH keys across 100 nodes).
- You are provisioning the machine that runs Terraform.
Ansible Roles
Don't write one giant Playbook. Roles allow you to package tasks, variables, and files into reusable components.
Directory Structure:
roles/
nginx/
tasks/main.yml
templates/nginx.conf.j2
vars/main.yml
mysql/
tasks/main.yml
playbook.ymlTerraform vs. Ansible
| Feature | Terraform | Ansible |
|---|---|---|
| Primary Goal | Provisioning (Infra) | Configuration (Software) |
| State | Maintains State File | Stateless (Checks current state) |
| Philosophy | Immutable (Replace VM) | Mutable (Update VM) |
| Language | HCL | YAML + Python (under hood) |
The Happy Marriage: Use Terraform to create the EC2 Instance. Pass the User Data script to bootstrap SSH. Then use Ansible to configure the application inside.