Infrastructure as Code (IaC) has transformed the way we provision, manage, and scale environments. In this post, we’ll explore how to automate infrastructure using popular tools like Terraform, Ansible, and GitHub Actions.
Why Automate?
Automation reduces manual errors, ensures consistency across deployments, and speeds up delivery cycles. Below are the key benefits:
- Version‑controlled infrastructure
- Rapid provisioning and scaling
- Reduced operational overhead
- Improved compliance and auditing
Getting Started with Terraform
Terraform lets you define cloud resources in declarative HCL files. Here’s a minimal example to launch an AWS EC2 instance:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
Run terraform init
, terraform plan
, then terraform apply
to provision.
Configuration Management with Ansible
Ansible complements Terraform by handling post‑provisioning configuration. Example playbook to install Nginx:
- hosts: webservers
become: true
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Start Nginx
service:
name: nginx
state: started
enabled: true
Execute with ansible-playbook -i inventory.yml site.yml
.
CI/CD Pipeline with GitHub Actions
Automate your IaC workflow using a GitHub Actions pipeline:
name: IaC Deploy
on:
push:
branches: [ main ]
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.6.0
- name: Terraform Init & Apply
run: |
terraform init
terraform apply -auto-approve
This pipeline runs on every push to main
, ensuring your infrastructure stays in sync with code.