Skip to content

Overview ๐Ÿ“˜

Terraform โ€” Common Commands & Examples

This cheat-sheet covers commonly used Terraform commands plus short examples and recommendations for module and backend usage.

Command What it does
terraform init Initialize working directory and download providers/modules.
terraform plan -out=tfplan Create an execution plan and save it.
terraform apply tfplan Apply a previously saved plan.
terraform apply -auto-approve Apply changes without interactive approval (use carefully).
terraform validate Validate config syntax and semantics.
terraform fmt Format Terraform files.
terraform state list List resources in state.
terraform import <type>.<name> <id> Import existing resource into state.
terraform workspace new <name> / select Use workspaces for environment separation.
terraform destroy Destroy resources managed by configuration.

Backend (remote state) example โ€” S3 + DynamoDB (AWS)

terraform {
    backend "s3" {
        bucket = "my-terraform-state"
        key    = "projectX/terraform.tfstate"
        region = "ap-south-1"
        dynamodb_table = "terraform-state-lock"
    }
}

Module usage example

module "vpc" {
    source = "git::https://github.com/example/terraform-aws-vpc.git?ref=v1.2.0"
    name   = "project-vpc"
    cidr   = "10.0.0.0/16"
}

Recommendations

  • Use remote state with locking (S3 + DynamoDB, Azure Storage + lease) for team collaboration.
  • Version modules and providers; pin provider versions in required_providers.
  • Keep state out of VCS; store sensitive outputs in secure stores.
  • Use CI to run terraform fmt, validate, and plan on PRs.

If you want, I can add an examples/terraform/ folder with a minimal reproducible module and backend example.