Terraform — Infrastructure as Declarative Code
Declare infrastructure resources in HCL — version-controlled, reproducible, diff before apply.
When to use
- Any cloud resource that needs to be reproducible across environments (dev/staging/prod)
Tradeoffs
- State drift: manual changes to infra cause plan surprises — always change via Terraform
- State file may contain sensitive values — protect with encryption and access control
- HCL (AWS)
- HCL (GCP)
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
backend "s3" {
bucket = "my-tf-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "tf-locks"
}
}
variable "env" { default = "prod" }
resource "aws_s3_bucket" "assets" {
bucket = "my-assets-${var.env}"
tags = { Environment = var.env }
}
output "bucket_name" { value = aws_s3_bucket.assets.bucket }
terraform {
required_providers {
google = { source = "hashicorp/google", version = "~> 5.0" }
}
backend "gcs" {
bucket = "my-tf-state"
prefix = "prod/terraform.tfstate"
}
}
variable "env" { default = "prod" }
variable "project" { default = "my-gcp-project" }
resource "google_storage_bucket" "assets" {
name = "my-assets-${var.env}"
project = var.project
location = "US"
labels = { environment = var.env }
}
output "bucket_name" { value = google_storage_bucket.assets.name }
Gotcha: Terraform state is the source of truth. If
terraform planshows unexpected changes, investigate before applying — something was changed outside of Terraform.