cheat-sheets

Terraform

Terraform is an infrastructure as code tool to provision, change, and version resources on any environment. Since 2023 it is source-available (BUSL) rather than open source; OpenTofu is the open source fork and a drop-in CLI replacement (tofu instead of terraform, same commands below). Cloud examples: Azure CLI (az), AWS CLI, gcloud (Google Cloud CLI), Civo.

Project Homepage: Terraform by HashiCorp Documentation: Terraform Docs, OpenTofu TF Registry: Terraform Registry

For state surgery, modules, moved/removed blocks and terraform test see Terraform State and Modules.

Format and Validate #

COMMANDDESCRIPTION
terraform fmt -recursiveReformat your configuration in the standard style (add -check in CI)
terraform validateCheck whether the configuration is valid

Initialize Working Directory #

COMMANDDESCRIPTION
terraform initPrepare your working directory for other commands
terraform init -upgradeUpgrade providers within version constraints
terraform init -migrate-stateMove state after changing the backend

Plan, Deploy and Cleanup #

COMMANDDESCRIPTION
terraform apply --auto-approveCreate or update infrastructure without confirmation prompt
terraform destroy --auto-approveDestroy previously-created infrastructure without confirmation prompt
terraform plan -out plan.outOutput the deployment plan to plan.out
terraform apply plan.outUse the plan.out to deploy infrastructure
terraform plan -destroyOutputs a destroy plan
terraform apply -target=aws_instance.myinstanceOnly apply/deploy changes to targeted resource
terraform apply -var myregion=us-east-1Pass a variable via CLI while applying a configuration
terraform apply -lock-timeout=60sWait for the state lock (locking is on by default for backends that support it)
terraform apply -refresh=falseDo not reconcile state file with real-world resources
terraform apply -replace=aws_instance.myinstanceForce recreation of one resource (replaces the old taint)
terraform plan -var-file=prod.tfvarsUse a variables file
terraform apply --parallelism=5Number of simultaneous resource operations
terraform apply -refresh-onlyReconcile the state file with real-world resources (the standalone terraform refresh is deprecated)
terraform providersGet information about providers used in the current configuration

Workspaces #

COMMANDDESCRIPTION
terraform workspace new myworkspaceCreate a new workspace
terraform workspace select defaultChange to a workspace
terraform workspace listList all workspaces

State Manipulation #

COMMANDDESCRIPTION
terraform state show aws_instance.myinstanceShow details stored in the Terraform state file
terraform state pull > terraform.tfstateOutput Terraform state to a file
terraform state mv aws_iam_role.my_ssm_role module.mymoduleMove a resource tracked via state to different module
terraform state replace-provider hashicorp/aws registry.custom.com/awsReplace an existing provider with another
terraform state listList all resources tracked in the Terraform state file
terraform state rm aws_instance.myinstanceUnmanage a resource, delete it from the Terraform state file

Import and Outputs #

COMMANDDESCRIPTION
terraform import resourcetype.myresource <id>Import a resource (or use an import {} block with terraform plan -generate-config-out=gen.tf)
terraform outputList all outputs
terraform output <output>List a specific output
terraform output -jsonList all outputs in JSON format

Terraform Cloud #

COMMANDDESCRIPTION
terraform loginLogin to Terraform Cloud with an API token
terraform logoutLogout from Terraform Cloud

Inspect and Debug #

COMMANDDESCRIPTION
terraform showShow the current state (terraform show plan.out for a saved plan)
terraform consoleEvaluate expressions interactively
terraform graph | dot -Tpng > graph.pngDependency graph (needs Graphviz)
terraform versionTerraform and provider versions
TF_LOG=DEBUG terraform planVerbose logging
terraform force-unlock <LOCK_ID>Clear a stuck state lock (only if no run is active)
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64Record provider checksums for several platforms

Minimal Example #

hcl
terraform {
  required_version = ">= 1.6"
  required_providers {
    civo = {
      source  = "civo/civo"
      version = "~> 1.0"
    }
  }
}

variable "region" {
  type    = string
  default = "LON1"
}

provider "civo" {
  region = var.region   # token from the CIVO_TOKEN environment variable
}

output "region" {
  value = var.region
}

Set sensitive values with environment variables such as TF_VAR_name or the provider’s own variable, never in committed .tfvars files.

Good Practice #

  • Commit .terraform.lock.hcl. Ignore .terraform/ and *.tfstate* in Git.
  • Use a remote backend (S3 with locking, Azure Storage, GCS or Terraform Cloud) for shared state. State can contain secrets.
  • Review terraform plan output before every apply; in CI run fmt -check, validate, plan.
  • Use terraform apply --auto-approve only in automation.
  • Policy and linting: tflint, trivy config, checkov.

See Also #

Search all sheets

Tip: / or Ctrl/Cmd+K to open, Esc to close.