核心 · Key Idea
In one line: Terraform is the IaC standard. After its 2024 license change to BSL (non-OSI), the community forked OpenTofu as a fully open-source alternative. API-compatible — migration is mostly swapping the binary name.
What it is#
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
backend "s3" {
bucket = "tfstate-prod"
key = "infra/main.tfstate"
region = "us-east-1"
dynamodb_table = "tfstate-lock"
encrypt = true
}
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "prod"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
}
resource "aws_s3_bucket" "media" {
bucket = "media-prod-${random_id.suffix.hex}"
force_destroy = false
}terraform init
terraform plan -out=tfplan
terraform apply tfplanAnalogy#
打个比方 · Analogy
Pre-Terraform = clicking around the cloud console + screenshots. Post-Terraform = an IKEA instruction sheet — anyone can reproduce the exact same furniture.
Key concepts#
ProviderCloud adapter
AWS / GCP / Azure / Cloudflare / GitHub — almost every cloud resource has one.
ResourceResource
A cloud object. Config is source of truth.
Data SourceData Source
Read-only — query an existing cloud resource's attributes.
ModuleModule
Reusable resource bundle, function-like.
BackendState backend
S3 / GCS / Terraform Cloud. **Remote + lock** — required for multi-person collaboration.
Workspace / multi-envWorkspace
Same code, multiple states (dev/staging/prod). Directory separation is often clearer.
PlanPlan
Computes diff without applying; CI posts it to PRs for review.
Workflow#
The PR flow is the security cornerstone of IaC — prod changes go through review.
Practical notes#
- Remote state + lock: S3 + DynamoDB / GCS / Terraform Cloud / Spacelift. Use it even solo — future teammates cost nothing.
- Modularize:
modules/network/,modules/eks-cluster/— reusable, testable. - Per-env directories:
envs/prod/main.tfreferencing modules + overriding vars — more intuitive than workspaces. - Secrets via secret backends: tfvars doesn't go to git, or use
vault_generic_secretdata source. prevent_destroy = trueon prod DB / critical buckets — guards against accidentaldestroy.- Drift detection: scheduled plan runs surface manual edits.
- Switching to OpenTofu:
opentofu init / plan / apply— drop-in binary. Major new features may diverge over time. - Don't lump everything into one root — multiple roots reduce blast radius.
Easy confusions#
Terraform / OpenTofu
Manages **cloud objects**.
Create / modify / delete resources.
Create / modify / delete resources.
Ansible
Manages **inside existing machines**.
Packages / files / services.
Packages / files / services.