DEV Community

Cover image for Day 18 - Infrastructure as Code (IaC) with Terraform
Rahul Joshi
Rahul Joshi

Posted on

Day 18 - Infrastructure as Code (IaC) with Terraform

Modern cloud infrastructure is too complex to manage manually.

Imagine creating:

  • 10 EC2 instances
  • 5 VPCs
  • 20 Security Groups
  • 15 IAM Roles
  • 3 Load Balancers
  • Kubernetes Clusters

using only a cloud console.

It quickly becomes:

Slow
Error-Prone
Difficult to Scale
Impossible to Audit
Enter fullscreen mode Exit fullscreen mode

This is why Infrastructure as Code (IaC) became one of the most important practices in modern DevOps and Cloud Engineering.


πŸ”— Resources


What is Infrastructure as Code (IaC)?

Infrastructure as Code (IaC) is the practice of managing infrastructure through code instead of manually creating resources.

Instead of clicking buttons:

AWS Console
      ↓
Create EC2
      ↓
Create Security Group
      ↓
Create VPC
Enter fullscreen mode Exit fullscreen mode

You write:

resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

And infrastructure gets created automatically.


Why Infrastructure as Code Matters

Before IaC, infrastructure management was painful.

Common problems included:

  • Manual mistakes
  • Configuration drift
  • Poor documentation
  • Difficult disaster recovery
  • Inconsistent environments

Example:

Developer Environment
        ↓
Works Perfectly
        ↓
Production Environment
        ↓
Different Configuration
        ↓
Application Fails
Enter fullscreen mode Exit fullscreen mode

IaC solves this problem by making environments reproducible.


Benefits of Infrastructure as Code

1. Consistency

Every environment is identical.

Dev
 ↓
QA
 ↓
Staging
 ↓
Production
Enter fullscreen mode Exit fullscreen mode

All built from the same code.


2. Version Control

Infrastructure becomes:

Git Commit
Pull Request
Code Review
Rollback
Audit Trail
Enter fullscreen mode Exit fullscreen mode

Infrastructure changes become trackable.


3. Automation

Entire environments can be created in minutes.


4. Disaster Recovery

If infrastructure is lost:

Git Repository
        ↓
terraform apply
        ↓
Infrastructure Restored
Enter fullscreen mode Exit fullscreen mode

5. Scalability

Large organizations can manage thousands of resources through code.


Infrastructure as Code Market Growth

Infrastructure automation has become a standard practice.

Today IaC is used by:

  • Cloud Engineers
  • DevOps Engineers
  • Platform Engineers
  • SRE Teams
  • Security Teams

Organizations running:

  • AWS
  • Azure
  • GCP
  • Kubernetes

almost always adopt some form of IaC.


Types of Infrastructure as Code

Declarative

You describe the desired state.

Example:

resource "aws_instance" "web" {
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

Tool decides how to create it.

Examples:

  • Terraform
  • CloudFormation
  • Bicep

Imperative

You define step-by-step instructions.

Example:

create_vpc()
create_subnet()
create_ec2()
Enter fullscreen mode Exit fullscreen mode

Examples:

  • Pulumi
  • Custom automation scripts

Popular Infrastructure as Code Tools


1. Terraform

Most popular multi-cloud IaC tool.

Created by:

HashiCorp

Supports:

  • AWS
  • Azure
  • GCP
  • Kubernetes
  • VMware
  • GitHub
  • Hundreds of providers

2. AWS CloudFormation (CFT)

AWS-native IaC service.

Supports:

  • VPC
  • EC2
  • IAM
  • S3
  • RDS
  • Lambda

Example:

Resources:
  MyBucket:
    Type: AWS::S3::Bucket
Enter fullscreen mode Exit fullscreen mode

3. Azure Bicep

Microsoft's modern IaC language.

Simplifies Azure Resource Manager templates.

Example:

resource storage 'Microsoft.Storage/storageAccounts@2022-09-01' = {
  name: 'mystorage'
}
Enter fullscreen mode Exit fullscreen mode

4. Pulumi

Modern Infrastructure as Code.

Uses programming languages:

  • Python
  • Go
  • TypeScript
  • C#
  • Java

Example:

import pulumi_aws as aws

bucket = aws.s3.Bucket("my-bucket")
Enter fullscreen mode Exit fullscreen mode

difference


Why Terraform Dominates IaC

Terraform became the industry standard because:

One Language
        ↓
Multiple Clouds
        ↓
Single Workflow
Enter fullscreen mode Exit fullscreen mode

Engineers can manage:

  • AWS
  • Azure
  • GCP
  • Kubernetes

using one tool.


Terraform Architecture

architecture


Terraform Basics

Understanding Terraform starts with four key concepts:

  • Providers
  • Resources
  • Variables
  • State

Terraform Providers

Providers allow Terraform to communicate with platforms.

Examples:

AWS Provider
Azure Provider
Google Provider
Kubernetes Provider
GitHub Provider
Enter fullscreen mode Exit fullscreen mode

Example:

provider "aws" {
  region = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode

Terraform now knows where to create resources.


Terraform Resources

Resources are actual infrastructure components.

Examples:

EC2 Instance
S3 Bucket
VPC
Security Group
IAM Role
Enter fullscreen mode Exit fullscreen mode

Example:

resource "aws_s3_bucket" "demo" {
  bucket = "my-demo-bucket"
}
Enter fullscreen mode Exit fullscreen mode

Terraform will create:

AWS S3 Bucket
Enter fullscreen mode Exit fullscreen mode

Terraform Variables

Variables make code reusable.

Without variables:

instance_type = "t2.micro"
Enter fullscreen mode Exit fullscreen mode

With variables:

variable "instance_type" {}

instance_type = var.instance_type
Enter fullscreen mode Exit fullscreen mode

Now different environments can use:

Dev β†’ t2.micro
QA β†’ t3.small
Prod β†’ t3.large
Enter fullscreen mode Exit fullscreen mode

Terraform State

Terraform keeps track of infrastructure using:

terraform.tfstate
Enter fullscreen mode Exit fullscreen mode

This file stores:

  • Resource IDs
  • Current state
  • Dependency mapping

Terraform compares:

Current State
        vs
Desired State
Enter fullscreen mode Exit fullscreen mode

and calculates required changes.


Terraform Workflow

Step 1

Write Code

resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

Step 2

Initialize

terraform init
Enter fullscreen mode Exit fullscreen mode

Downloads providers.


Step 3

Validate

terraform validate
Enter fullscreen mode Exit fullscreen mode

Checks syntax.


Step 4

Preview

terraform plan
Enter fullscreen mode Exit fullscreen mode

Shows changes before execution.


Step 5

Apply

terraform apply
Enter fullscreen mode Exit fullscreen mode

Creates infrastructure.


Deep Terraform Example

Let's create a simple AWS infrastructure.


Provider

provider "aws" {
  region = "us-east-1"
}
Enter fullscreen mode Exit fullscreen mode

Variable

variable "instance_type" {
  default = "t2.micro"
}
Enter fullscreen mode Exit fullscreen mode

Security Group

resource "aws_security_group" "web_sg" {

  name = "web-sg"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
Enter fullscreen mode Exit fullscreen mode

EC2 Instance

resource "aws_instance" "web" {

  ami           = "ami-123456"
  instance_type = var.instance_type

  vpc_security_group_ids = [
    aws_security_group.web_sg.id
  ]

  tags = {
    Name = "Terraform-Web"
  }
}
Enter fullscreen mode Exit fullscreen mode

What Happens Behind the Scenes?

Behined the Scene


Terraform File Structure

Typical project:

terraform-project/

β”œβ”€β”€ main.tf
β”œβ”€β”€ variables.tf
β”œβ”€β”€ outputs.tf
β”œβ”€β”€ terraform.tfvars
└── providers.tf
Enter fullscreen mode Exit fullscreen mode

Best Practices

Use Remote State

Store state in:

S3
Azure Storage
GCS
Terraform Cloud
Enter fullscreen mode Exit fullscreen mode

Never store production state locally.


Use Modules

Avoid repeating code.

module "vpc" {
  source = "./modules/vpc"
}
Enter fullscreen mode Exit fullscreen mode

Use Version Control

Infrastructure should always live in Git.


Enable Code Reviews

Treat infrastructure like application code.


Separate Environments

Dev
QA
Staging
Production
Enter fullscreen mode Exit fullscreen mode

should have separate state files.


Infrastructure as Code in DevOps Pipeline

Developer Pushes Terraform
          ↓
Pull Request
          ↓
Code Review
          ↓
terraform validate
          ↓
terraform plan
          ↓
Security Scan
          ↓
terraform apply
          ↓
Infrastructure Created
Enter fullscreen mode Exit fullscreen mode

Security Considerations

Never store:

AWS Keys
Passwords
Tokens
Secrets
Enter fullscreen mode Exit fullscreen mode

inside Terraform code.

Use:

  • AWS Secrets Manager
  • Azure Key Vault
  • HashiCorp Vault

instead.


Final Thoughts

Infrastructure as Code transformed how cloud infrastructure is managed.

Instead of:

Manual Infrastructure
Enter fullscreen mode Exit fullscreen mode

we now have:

Version Controlled Infrastructure
Enter fullscreen mode Exit fullscreen mode

Among all IaC tools:

  • Terraform dominates multi-cloud environments
  • CloudFormation is ideal for AWS-centric teams
  • Bicep is excellent for Azure
  • Pulumi is attractive for developers who prefer real programming languages

For anyone pursuing:

  • DevOps
  • Cloud Engineering
  • Platform Engineering
  • Site Reliability Engineering

Infrastructure as Code is no longer optionalβ€”it is a fundamental skill of modern cloud operations.

Top comments (0)