Infrastructure as Code with Terraform
Managing infrastructure manually through cloud consoles is error-prone, hard to scale, and lacks accountability. Infrastructure as Code (IaC) solves this problem by defining cloud components in text configuration files that can be versioned, reviewed, and automated.
HashiCorp Terraform is the leading multi-cloud declarative IaC tool, using the HashiCorp Configuration Language (HCL).
Declarative Lifecycle Flow
Terraform uses a declarative paradigm. You define the desired end-state of your architecture, and Terraform automatically calculates the execution path necessary to provision or modify the environment.
Writing a Terraform Configuration
Here is a sample configuration to provision a Virtual Private Cloud (VPC), a Public Subnet, and an EC2 Instance on Amazon Web Services (AWS):
# provider.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
}
}
provider "aws" {
region = "us-east-1"
}
# network.tf
resource "aws_vpc" "dev_vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "dev-vpc"
}
}
resource "aws_subnet" "public_subnet" {
vpc_id = aws_vpc.dev_vpc.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
tags = {
Name = "dev-public-subnet"
}
}
# compute.tf
resource "aws_instance" "web_server" {
ami = "ami-0c7217cdde317cfec" # Ubuntu AMI
instance_type = "t2.micro"
subnet_id = aws_subnet.public_subnet.id
tags = {
Name = "dev-web-server"
}
}
The State File (terraform.tfstate)
The state file is the source of truth for Terraform. It maps real-world cloud resources to your configuration files.
[!CAUTION] Never check state files directly into source control. They contain sensitive raw data (like database passwords, API tokens, and private keys). Always configure a remote backend (like AWS S3 or HashiCorp Cloud) with state locking enabled (using DynamoDB) to enable safe collaborative workflows.
Workflow Commands
- Initialize Directory:
terraform init(downloads providers and configures state backend). - Format Check:
terraform fmt&terraform validate. - Preview Plan:
terraform plan(generates dry-run resource operations). - Apply Changes:
terraform apply(provisions resources). - Destroy Infrastructure:
terraform destroy(tears down all managed infrastructure).
Written by Swapnil
DevOps & Infrastructure Engineer, focusing on container scaling, secure automated deployment pipelines, and cloud state architecture.