Terraform for Beginners: Infrastructure as Code Explained
Clicking around a cloud console is fine once. For anything you need to repeat, review or recover, describe infrastructure in code. Terraform reads configuration files and creates, updates or deletes cloud resources to match.
A first configuration
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_s3_bucket" "assets" {
bucket = "acme-shop-assets-prod"
tags = {
Project = "shop"
Environment = "prod"
}
}
resource "aws_s3_bucket_public_access_block" "assets" {
bucket = aws_s3_bucket.assets.id # reference another resource
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
The workflow
terraform init # download providers, set up the backend
terraform fmt # format files
terraform validate # check syntax and references
terraform plan # show what would change
terraform apply # make the changes (asks for confirmation)
terraform destroy # delete everything this config manages
Always read the plan. Lines with + create, ~ update in place, and -/+ replace (destroy then create), which can mean downtime or data loss.
State
Terraform records what it created in a state file, mapping your code to real resource IDs. Losing or corrupting it is painful, so teams store it remotely with locking (covered in the next article) rather than on a laptop.
Why teams use it
- Changes are reviewed in pull requests like application code.
- Environments are reproducible: staging really matches production.
- One tool works across many providers: AWS, Google Cloud, Azure, Cloudflare, GitHub, Datadog and more.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.