terraform init
terraform init -upgrade
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" { region = "us-east-1" }
terraform version
terraform validate
terraform fmt
terraform plan
terraform plan -out=tfplan
terraform apply
terraform apply tfplan
terraform apply -auto-approve
terraform destroy
terraform destroy -target=aws_instance.web
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = "t3.micro"
tags = { Name = "web-01" }
}
variable "ami_id" {
type = string
default = "ami-0123456789"
}
output "public_ip" {
value = aws_instance.web.public_ip
}
locals {
env = "prod"
}
name = "${local.env}-web-01"
terraform apply -var-file="prod.tfvars"
ami_id = "ami-0abcdef1234"
terraform state list
terraform state show aws_instance.web
terraform state mv aws_instance.web aws_instance.web01
terraform state rm aws_instance.old
terraform {
backend "s3" {
bucket = "tf-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "tf-locks"
}
}
terraform import aws_instance.web i-0abc123
terraform state pull > state.json
terraform force-unlock LOCK_ID
terraform apply -refresh-only
module "vpc" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
}
terraform get -update
terraform workspace new staging
terraform workspace select prod
terraform workspace list
| Symptom | Fix |
|---|---|
| Error acquiring the state lock | wait for the other apply, or force-unlock if it's stale |
| Resource already exists (outside TF) | terraform import to bring it under management |
| Plan shows unexpected drift | someone changed infra manually — reconcile or ignore_changes |
| Provider version conflict | pin version in required_providers, re-run init -upgrade |
| Destroy deletes more than expected | check for cascading dependencies, use -target sparingly |
| Circular dependency error | break the cycle with a data source or restructure resources |
| Command | Purpose |
|---|---|
| terraform plan -out=tfplan | safe saves an exact plan to apply later |
| terraform apply -auto-approve | caution no confirmation — CI pipelines only |
| terraform destroy | destructive tears down all tracked resources |
| terraform force-unlock | caution only if lock is confirmed stale |
| terraform graph | outputs the dependency graph (pipe to Graphviz) |
| terraform console | interactive REPL for testing expressions |