How to Use Terraform Without Destroying Production
The first time I ran terraform apply against a production account, I watched the plan scroll by for ten minutes and saw "1 to add, 0 to change, 1 to destroy." The "1 to destroy" was a database I cared about. I panicked, ctrl-C'd, and learned two things: Terraform is honest about what it's going to do, and you should always read the plan. The second time I ran terraform apply, I read the plan, the destroy was correct, and the world didn't end. That's Terraform in one sentence: it's a tool that forces you to think about infrastructure changes before you make them, and it's terrifying until you trust it, and then it's liberating.
This article is the Terraform guide I wish I'd had. We'll cover the model, the CLI, state, modules, the production patterns, and the ways I've seen teams get into trouble. By the end you should be able to write Terraform that you'd be comfortable running on a Friday afternoon-though you shouldn't run it on a Friday afternoon.
What Terraform Actually Is
Terraform is a declarative infrastructure-as-code tool. You write HCL (HashiCorp Configuration Language) describing what infrastructure you want-a VPC, some subnets, a database, an IAM role-and Terraform figures out how to get there from where you are. It calls cloud APIs, tracks state in a file, and shows you a plan before applying changes.
The mental model: you write desired state, Terraform compares it to actual state (via cloud APIs and the state file), computes a diff, and applies that diff. The state file is the bridge-it's Terraform's record of what it thinks exists, so it doesn't have to query every resource on every run.
| Tool | Model | Language | State | Sweet spot |
|---|---|---|---|---|
| Terraform | Declarative | HCL | Yes (state file) | Multi-cloud infra |
| Pulumi | Declarative | TypeScript/Python/Go | Yes | Developers who prefer real languages |
| CloudFormation | Declarative | YAML/JSON | Yes (managed) | AWS-only shops |
| AWS CDK | Imperative to declarative | TS/Python/Java | Yes (via CFN) | AWS developers wanting code |
| Ansible | Imperative | YAML | No | Configuration management, not infra provisioning |
| Crossplane | Declarative | K8s YAML | Yes (in etcd) | K8s-native infra control |
Terraform remains the default for multi-cloud infrastructure provisioning. Pulumi is its main modern competitor; the choice is largely about whether you'd rather write HCL or TypeScript.
Architecture at a Glance
CodeCopy Your HCL files
(main.tf, variables.tf, etc.)
|
v
+-------------------+
| Terraform CLI |
| - parse HCL |
| - build graph |
| - plan diff |
+---------+---------+
|
| reads/writes
v
+-------------------+ +-------------------+
| State file | <----> | Cloud APIs |
| (S3 + DynamoDB) | | (AWS/GCP/Azure) |
+-------------------+ +-------------------+
|
v
+-------------------+
| Plan output |
| (review before |
| apply) |
+-------------------+
The state file is the center of Terraform's design. It maps your HCL resources to real cloud resources by ID. It stores last-known attribute values so Terraform can detect drift. It enables locking so two engineers don't apply simultaneously.
Prerequisites
- The Terraform CLI. Install from HashiCorp's repo (don't use the version in your distro's package manager; it's often ancient). On macOS:
brew tap hashicorp/tap && brew install hashicorp/tap/terraform. - An AWS account (we'll use AWS for examples). Or GCP, Azure, any of the 100+ providers.
- AWS credentials. Use
aws configureto set up a profile, or use OIDC (covered later). - A code editor with HCL support. VS Code + HashiCorp Terraform extension.
-
terraform-lsfor IDE features. -
tflintfor linting. -
tfsecorcheckovfor security scanning.
Check:
BashCopy
plaintext
terraform version
Terraform v1.9.0
markdown
Terraform 1.x is stable and backwards-compatible. Don't use 0.x in 2024.
Project Layout
The layout I use for anything beyond toy projects:
CodeCopy
plaintext
infra/
versions.tf # required_version, required_providers
backend.tf # state backend config
providers.tf # provider configurations
variables.tf # input variable declarations
main.tf # top-level resources and module composition
outputs.tf # output values
locals.tf # locals
modules/
vpc/
main.tf
variables.tf
outputs.tf
eks/
...
environments/
staging/
backend.tf # state per env
main.tf # module { source = "../../modules/vpc" ... }
tfvars.tf
prod/
...
markdown
Two patterns for multi-environment:
- Workspaces: one directory, switched via
terraform workspace select. I don't recommend this. Workspaces share state configuration, which makes permission separation hard, and surprises you when you forget which workspace you're in. - Directories: one directory per environment, each with its own backend and tfvars. More verbose, much safer. This is the pattern I use.
For larger setups, layer Terragrunt on top to DRY up the per-env boilerplate.
HCL Basics
HCL has a few core constructs:
Resources. The main building block. A resource is an infrastructure object.
hclCopy
terraform
resource "aws_s3_bucket" "uploads" {
bucket = "myorg-uploads"
tags = {
Name = "uploads"
ManagedBy = "terraform"
}
}
plaintext
The resource type is aws_s3_bucket. The local name is uploads. Reference it elsewhere as aws_s3_bucket.uploads.
Data sources. Read-only lookups of existing infrastructure.
hclCopy
terraform
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
Reference: data.aws_caller_identity.current.account_id
markdown
Variables. Inputs to the module.
hclCopy
terraform
variable "environment" {
description = "Deployment environment"
type = string
default = "staging"
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "environment must be staging or production."
}
}
markdown
Locals. Computed values, scoped to the module.
hclCopy
terraform
locals {
common_tags = {
ManagedBy = "terraform"
Environment = var.environment
Project = "myapp"
}
bucket_name = "myapp-${var.environment}-uploads"
}
markdown
Outputs. Values exported from the module.
hclCopy
terraform
output "bucket_arn" {
description = "ARN of the uploads bucket"
value = aws_s3_bucket.uploads.arn
}
markdown
State Management
The state file is the single most important thing to get right. Rules:
- Remote state, always. Local state is fine for tutorials and nothing else. In a team, use remote state.
- Locking. Your backend must support locking, or two engineers applying simultaneously will corrupt state.
- Encryption. State contains secrets (RDS passwords, IAM access keys). The backend must encrypt at rest.
- Access control. Limit who can read state. Anyone with read access can see your secrets.
- Back it up. Even with versioning on the state bucket, occasionally run
terraform state pull > backup.tfstate.
The standard AWS pattern:
hclCopy
terraform
backend.tf
terraform {
required_version = ">= 1.7.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.50"
}
}
backend "s3" {
bucket = "myorg-terraform-state"
key = "myapp/staging/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
plaintext
The S3 bucket must have versioning enabled. The DynamoDB table (named terraform-locks, with primary key LockID) provides locking. Create both with a bootstrap script-not Terraform, because Terraform needs them to exist before it can manage state.
BashCopy
shell
bootstrap.sh - run once per AWS account
aws s3api create-bucket --bucket myorg-terraform-state --region us-east-1
aws s3api put-bucket-versioning --bucket myorg-terraform-state \
--versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket myorg-terraform-state \
--server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
aws dynamodb create-table --table-name terraform-locks \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
markdown
Never commit terraform.tfstate to git. It contains secrets, and once they're in git history, they're compromised forever. Add it to .gitignore.
Providers and the Registry
Providers translate Terraform's HCL into cloud API calls. The official registry is at registry.terraform.io. Each provider has its own release cadence-pin to a minor version (~> 5.50 means >= 5.50, < 6.0).
hclCopy
terraform
providers.tf
provider "aws" {
region = var.aws_region
default_tags {
tags = local.common_tags
}
}
markdown
default_tags applies to every resource the provider creates. Useful for cost allocation and "find everything Terraform manages" queries.
A Real Example: VPC, RDS, EKS
Here's a real, working configuration for an AWS VPC with EKS and RDS. It's opinionated and uses modules from the registry.
hclCopy
terraform
versions.tf
terraform {
required_version = ">= 1.7.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.50"
}
kubernetes = {
source = "hashicorp/kubernetes"
version = "~> 2.30"
}
helm = {
source = "hashicorp/helm"
version = "~> 2.13"
}
}
}
plaintext
hclCopy
terraform
variables.tf
variable "environment" {
type = string
validation {
condition = contains(["staging", "production"], var.environment)
error_message = "Must be staging or production."
}
}
variable "aws_region" {
type = string
default = "us-east-1"
}
variable "app_name" {
type = string
default = "myapp"
}
variable "db_password" {
type = string
sensitive = true
}
plaintext
hclCopy
terraform
main.tf
data "aws_caller_identity" "current" {}
data "aws_availability_zones" "available" {
state = "available"
filter {
name = "opt-in-status"
values = ["opt-in-not-required"]
}
}
locals {
common_tags = {
ManagedBy = "terraform"
Environment = var.environment
Project = var.app_name
}
azs = slice(data.aws_availability_zones.available.names, 0, 3)
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.8"
name = "${var.app_name}-${var.environment}"
cidr = "10.0.0.0/16"
azs = local.azs
private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
database_subnets = ["10.0.21.0/24", "10.0.22.0/24", "10.0.23.0/24"]
enable_nat_gateway = true
single_nat_gateway = var.environment == "staging"
enable_dns_hostnames = true
enable_dns_support = true
public_subnet_tags = {
"kubernetes.io/role/elb" = 1
}
private_subnet_tags = {
"kubernetes.io/role/internal-elb" = 1
}
tags = local.common_tags
}
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "~> 20.20"
name = "${var.app_name}-${var.environment}"
version = "1.30"
endpoint_public_access = true
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnets
enable_irsa = true
eks_managed_node_groups = {
main = {
min_size = var.environment == "production" ? 3 : 1
max_size = var.environment == "production" ? 10 : 3
desired_size = var.environment == "production" ? 3 : 1
instance_types = ["t3.large"]
capacity_type = "ON_DEMAND"
labels = {
Environment = var.environment
}
}
}
tags = local.common_tags
}
module "db" {
source = "terraform-aws-modules/rds/aws"
version = "~> 6.5"
identifier = "${var.app_name}-${var.environment}"
engine = "postgres"
engine_version = "16.3"
instance_class = var.environment == "production" ? "db.t4g.medium" : "db.t4g.micro"
allocated_storage = 20
db_name = "app"
username = "app"
password = var.db_password
vpc_id = module.vpc.vpc_id
db_subnet_ids = module.vpc.database_subnets
create_db_subnet_group = true
backup_retention_period = var.environment == "production" ? 14 : 1
deletion_protection = var.environment == "production"
skip_final_snapshot = var.environment != "production"
tags = local.common_tags
}
resource "aws_security_group" "db" {
name = "${var.app_name}-db-access"
description = "Allow EKS to access RDS"
vpc_id = module.vpc.vpc_id
ingress {
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [module.eks.node_security_group_id]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = local.common_tags
}
plaintext
hclCopy
terraform
outputs.tf
output "vpc_id" {
value = module.vpc.vpc_id
}
output "eks_cluster_name" {
value = module.eks.cluster_name
}
output "eks_cluster_endpoint" {
value = module.eks.cluster_endpoint
sensitive = true
}
output "rds_endpoint" {
value = module.db.db_instance_endpoint
sensitive = true
}
plaintext
That's a real, working infra setup. Apply with:
BashCopy
plaintext
terraform init # download providers, configure backend
terraform plan # show what will change
terraform apply # apply changes (will prompt for confirmation)
markdown
Modules: Writing and Using
Modules are the unit of reuse in Terraform. Any directory with .tf files is a module. The pattern:
CodeCopy
plaintext
modules/
vpc/
main.tf
variables.tf
outputs.tf
versions.tf
README.md
plaintext
Call from a parent:
hclCopy
terraform
module "vpc" {
source = "./modules/vpc"
environment = var.environment
cidr = "10.0.0.0/16"
}
plaintext
For sharing across repos, publish to the Terraform Registry or a private registry (like Terraform Cloud's). Pin to a version:
hclCopy
terraform
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.8.0"
# ...
}
markdown
The community registry has high-quality modules for VPC, EKS, RDS, ALB, and most common AWS resources. Use them-the terraform-aws-modules org is well-maintained and battle-tested.
Loops and Conditionals
count for "create N of these":
hclCopy
terraform
resource "aws_iam_user" "users" {
count = length(var.user_names)
name = var.user_names[count.index]
}
markdown
for_each for "create one per key in a map":
hclCopy
terraform
resource "aws_s3_bucket" "buckets" {
for_each = toset(var.bucket_names)
bucket = each.value
}
markdown
for expressions for transforming lists/maps:
hclCopy
terraform
locals {
upper_names = [for name in var.user_names : upper(name)]
tags_map = { for k, v in var.tags : k => v if v != null }
}
markdown
dynamic blocks for generating nested blocks:
hclCopy
terraform
resource "aws_security_group" "main" {
name = "main"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}
markdown
Conditionals via count:
hclCopy
terraform
resource "aws_db_instance" "main" {
count = var.create_db ? 1 : 0
# ...
}
terraform
Reference as aws_db_instance.main[0].endpoint to handle the case where it's not created.
CLI Workflow
The day-to-day loop:
BashCopy
plaintext
terraform init # set up backend and providers
terraform validate # syntax and config validation
terraform fmt # format HCL
terraform plan # show the diff
terraform apply # apply the diff
terraform destroy # tear everything down (use sparingly)
plaintext
Operations you'll need occasionally:
BashCopy
plaintext
terraform state list # what's in state
terraform state show aws_s3_bucket.uploads # details of one resource
terraform state mv aws_s3_bucket.old aws_s3_bucket.new # rename without destroy/create
terraform state rm aws_s3_bucket.uploads # remove from state without destroying cloud resource
terraform import aws_s3_bucket.uploads my-bucket-name # bring existing cloud resource under Terraform
terraform force-unlock # if a state lock is stuck
terraform apply -replace=aws_s3_bucket.uploads # taint-and-apply in one step
markdown
The import command is critical when adopting Terraform for existing infrastructure. The pattern: import, run plan (expect a large diff because Terraform doesn't know about default values), edit your HCL until plan shows "No changes", commit.
In Terraform 1.5+, you can also write import { ... } blocks directly in HCL and use terraform plan -generate-config-out=generated.tf to have Terraform write the HCL for you. Vastly easier than the CLI-only workflow.
Drift Detection
Drift = reality no longer matches state, because someone changed something outside Terraform (console click, CLI command, another tool). Detect with:
BashCopy
shell
terraform plan -detailed-exitcode
exit code 0: no changes
exit code 1: error
exit code 2: changes detected
markdown
Run this in CI on a schedule. Alert on non-zero exit codes. Drift is a leading indicator of "someone is doing things they shouldn't" or "Terraform isn't being used for everything."
For remediation, you can either:
- Update Terraform to match reality (if the drift was intentional).
- Run
terraform applyto revert reality to match Terraform (if the drift was a mistake).
For resources that legitimately change outside Terraform (autoscaling groups modifying instance counts, Lambda concurrency settings), use lifecycle { ignore_changes = [...] } so Terraform doesn't try to revert them.
Backends and CI/CD
For team workflows, run Terraform from CI/CD, not local machines. The pattern:
- Engineer opens PR with Terraform changes.
- CI runs
terraform fmt -check,terraform validate,tflint,tfsec. - CI runs
terraform planand posts the plan as a PR comment. - Reviewer approves.
- On merge, CI runs
terraform apply.
Tools that automate this:
| Tool | Model | Sweet spot |
|---|---|---|
| Atlantis | Self-hosted, PR-driven | Teams wanting full control |
| Terraform Cloud | SaaS, PR-driven | Teams wanting managed |
| GitHub Actions + OIDC | DIY | Small teams, simple workflows |
| Digger | Open-source, PR-driven | Terraform Cloud alternative |
| Spacelift | SaaS, policy-driven | Larger orgs |
A minimal GitHub Actions setup with OIDC:
YAMLCopy
yaml
.github/workflows/terraform.yml
name: Terraform
on:
push:
branches: [main]
pull_request:
paths: [infra/**]
permissions:
id-token: write
contents: read
pull-requests: write
jobs:
plan:
runs-on: ubuntu-latest
defaults:
run:
working-directory: infra/environments/staging
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/terraform-ci aws-region: us-east-1
- uses: hashicorp/setup-terraform@v3 with: terraform_version: "1.9.0"
- run: terraform init
- run: terraform fmt -check
- run: terraform validate
- id: plan run: terraform plan -no-color continue-on-error: true
- name: Comment plan on PR if: github.event_name == 'pull_request' uses: actions/github-script@v7 env: PLAN: ${{ steps.plan.outputs.stdout }} with: script: | const output =
\\\n${process.env.PLAN}\n\`; github.rest.issues.createComment({ ...context.repo, issue_number: context.issue.number, body:Terraform plan:\n${output}`, });
apply:
needs: plan
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/terraform-ci aws-region: us-east-1
- uses: hashicorp/setup-terraform@v3
- run: cd infra/environments/production && terraform init && terraform apply -auto-approve
` `markdown
The environment: production block adds a manual approval gate before apply runs. OIDC means no long-lived AWS keys in the repo.
Production Patterns
For multi-environment setups, my preferred structure:
`
CodeCopy
`plaintext
modules/
vpc/
eks/
rds/
envs/
staging/
backend.tf
main.tf # module "vpc" { source = "../../modules/vpc" ... }
tfvars.tf
production/
backend.tf
main.tf
tfvars.tf
`markdown
`
Each env has its own state file, its own backend, and its own IAM role. Permissions can be scoped so the staging CI can't touch production state. This is more verbose than workspaces, but much safer.
For larger setups with many envs or many modules, Terragrunt helps DRY up the per-env config. Worth it past 3-4 envs.
Security
Secrets in state. Terraform state contains whatever attributes your resources have, including passwords (aws_db_instance.password), private keys (tls_private_key.private_key_pem), and access tokens. Mark sensitive variables with sensitive = true (prevents them from appearing in logs), but understand that they're still in the state file. Restrict access to the state bucket.
Use OIDC for cloud auth. Same pattern as GitHub Actions. Don't create long-lived IAM users for Terraform.
Scan with tfsec or checkov. Both detect common mistakes: S3 buckets without encryption, security groups open to 0.0.0.0/0, IAM policies that are too broad. Run in CI.
Use Sentinel or OPA for policy. For larger orgs, enforce policies like "no S3 buckets without encryption" or "no security group rules open to the internet" at the Terraform Cloud / Terraform Enterprise level.
Don't use terraform.tfvars for secrets. Use a secrets manager (AWS Secrets Manager, Vault) and read with a data source:
`
hclCopy
`terraform
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "myapp/db/password"
}
module "db" {
# ...
password = jsondecode(data.aws_secretsmanager_secret_version.db_password.secret_string)["password"]
}
`markdown
`
Cost Estimation and Policy as Code
Infracost shows cost estimates for your Terraform in PR comments. Free for OSS projects, paid for private. Worth it for any team that has ever been surprised by a cloud bill.
`
BashCopy
shell
infracost breakdown --path infra/environments/staging --format table
`
checkov / tfsec / terrascan for security scanning. All similar; pick one and integrate into CI.
OPA / Sentinel for policy enforcement. Examples: require all S3 buckets have encryption, require all RDS instances have backup retention > 7 days, require all EKS clusters have logging enabled.
Common Mistakes
Committing terraform.tfstate to git. Don't. Add to .gitignore from day one. If it happens, rotate every secret in the file and rewrite git history.
Hardcoding AWS keys. Use profiles, instance metadata, or OIDC. Never access_key = "AKIA..." in HCL.
Using latest for provider versions. Pin to ~> 5.50 or a specific version. A new provider major version can break your config.
No terraform validate in CI. A typo that breaks Terraform shouldn't make it to a branch where someone runs apply.
Missing tags. Untagged resources are unkillable. Use default_tags on the provider so every resource gets tagged.
terraform apply without reading the plan. Always read the plan, especially the destroy operations. Especially on Friday.
Forgetting depends_on for implicit dependencies. Terraform usually figures out dependencies from variable references, but module-to-module dependencies sometimes need explicit depends_on.
One giant main.tf with 500 resources. Split into modules. A file with 500 resources is unmaintainable.
Editing state by hand. Don't. Use terraform state mv, terraform state rm, etc. Editing the JSON by hand is how you end up with corrupted state.
Troubleshooting
State lock stuck. terraform force-unlock <lock-id>. Only do this if you're sure no other Terraform process is running. The most common cause: a CI job was cancelled mid-apply.
"Provider produced inconsistent result after apply." The provider returned a different value than Terraform expected. Usually a provider bug. Update the provider, or open an issue. Workaround: terraform apply -target=<resource> to apply just that resource.
"Resource not found" during plan. The resource was deleted outside Terraform. Either restore it, or terraform state rm to remove it from state, then update your HCL.
Drift on every plan. Something is changing the resource outside Terraform-maybe an autoscaler, another tool, or a Lambda. Find and fix the source, or accept the drift and use lifecycle { ignore_changes = [...] }.
Importing a resource shows a huge diff. Terraform doesn't know about provider defaults. Read the provider docs, add the attributes that match the real resource, repeat until plan shows no changes.
Stuck on destroy. Usually a resource that depends on another resource that's already gone. Look for resources in a deleting state in the cloud console; often you need to manually delete the dependency. terraform state rm to remove from state if you've cleaned up manually.
Provider version conflicts. Two modules require different versions of the same provider. Pin the provider version at the top level and ensure all modules are compatible.
Alternatives
| Tool | Sweet spot | Why switch |
|---|---|---|
| Pulumi | Real languages, testing | You'd rather write TypeScript than HCL |
| CloudFormation | AWS-only | You're all-in on AWS and want managed state |
| AWS CDK | AWS, developer-friendly | Same as above, with code |
| Crossplane | K8s-native | You want infra controlled via Kubernetes API |
| Ansible | Configuration management | For configuring instances, not provisioning infra |
| OpenTofu | OSS Terraform fork | License concerns; otherwise identical |
If you're starting fresh and your team is comfortable with HCL, Terraform remains the safer choice for multi-cloud. If you're a TypeScript-heavy team that wants testing and abstractions, Pulumi is excellent.
Real-World Use Cases
- Multi-environment infra. Staging and production AWS accounts, identical configs, different variables. The canonical Terraform use case.
- Multi-cloud. AWS for compute, Cloudflare for DNS and CDN, GitHub for OIDC. Terraform's provider model makes this easy.
- Disaster recovery. Stand up a copy of production in another region from Terraform. Test by destroying and rebuilding.
- Onboarding new accounts. Baseline IAM, CloudTrail, Config, security hubs, all from one Terraform module applied per account.
- Tenant provisioning. SaaS apps that give each customer a dedicated VPC, database, and IAM role. Terraform Enterprise / Terraform Cloud for the orchestration.
Conclusion
Terraform, done well, is one of the few tools that genuinely improves a team's infrastructure reliability. The discipline it forces-review the plan, run from CI, separate state per environment, scan for security, estimate cost-transfers to everything else you do. Done badly, it's another pile of HCL nobody understands, with a state file nobody wants to touch.
The pattern that has served me best: treat Terraform like production code. Review it. Test it. Pin versions. Document modules. Run from CI with OIDC, not local machines with long-lived keys. Have a rollback plan for every change. The teams that do this ship infrastructure changes safely; the teams that don't eventually have a terraform destroy disaster story.
Originally published on Mango Developer.
原文:https://www.a8q9.cn/en/article/how-to-use-terraform-without-destroying-production-34a406.html