Terraform

Complete HashiCorp Terraform CLI reference, state management, and HCL patterns

text

๐Ÿ“˜ Introduction

Terraform by HashiCorp is an open-source Infrastructure as Code (IaC) tool used to provision and manage cloud, on-prem, and SaaS infrastructure through configuration files written in HCL (HashiCorp Configuration Language).

With Terraform, you define infrastructure in a declarative format, allowing for versioning, reusability, automation, and consistency across environments.

[!NOTE] OpenTofu Compatibility: OpenTofu is the open-source, community-driven fork of Terraform (Linux Foundation). Almost all CLI commands and HCL syntax (terraform ... โ‡„ tofu ...) are drop-in interchangeable.

๐Ÿ”น Key Concepts

TermDescription
ProvidersPlugins responsible for managing specific platforms (e.g., AWS, Azure, GCP, Kubernetes).
ResourcesInfrastructure components declared to be managed (e.g., EC2, S3, VPC).
Data SourcesRead-only infrastructure queries fetching existing cloud resources outside Terraform.
VariablesInput values passed into configurations for modularity.
OutputsReturn values that Terraform displays or passes to other configurations.
State FileTracks real-world resources mapped to configuration (terraform.tfstate).
ModulesSelf-contained packages of Terraform configurations that create reusable components.

๐ŸŒ Terraform Commands Quick Reference

๐ŸŸข Beginner Commands (Click to Expand)

๐Ÿ”น Check Version

terraform version

๐Ÿ”น Initialize Working Directory

terraform init

๐Ÿ”น Validate Configuration

terraform validate

๐Ÿ”น Format Code

terraform fmt
terraform fmt -recursive

๐Ÿ”น Show Help

terraform -help
terraform plan -help

๐ŸŸก Intermediate Commands (Click to Expand)

๐Ÿ”น Plan Infrastructure Changes

terraform plan
terraform plan -out=tfplan

๐Ÿ”น Apply Infrastructure Changes

terraform apply
terraform apply -auto-approve
terraform apply tfplan

๐Ÿ”น Targeted Recreation (Modern Replacement for Taint)

terraform apply -replace="aws_instance.web"

๐Ÿ”น Destroy Infrastructure

terraform destroy
terraform destroy -auto-approve

๐Ÿ”น Output Variables

terraform output
terraform output -json
terraform output instance_ip

๐Ÿ”น Manage State

terraform state list
terraform state show <resource>
terraform state mv <old_name> <new_name>
terraform state rm <resource>

๐Ÿ”ด Advanced Commands (Click to Expand)

๐Ÿ”น Target Specific Resources

terraform apply -target=aws_instance.example
terraform destroy -target=module.vpc

๐Ÿ”น Work with Modules

terraform get
terraform init -upgrade

๐Ÿ”น Backend Configuration

terraform init -backend-config="key=my-state.tfstate" -reconfigure

๐Ÿ”น Import Existing Infrastructure (CLI & Modern Import Block)

# Classic CLI import
terraform import aws_instance.example i-12345678

# Modern Terraform 1.5+ declarative generation
terraform plan -generate-config-out=generated.tf

๐Ÿ”น Native Automated Tests (Terraform 1.6+)

terraform test
terraform test -verbose

๐Ÿ”น Graph Dependency Tree

terraform graph | dot -Tpng > graph.png

๐Ÿ”น Force Unlock State

terraform force-unlock <LOCK_ID>

๐ŸŸข Beginner Commands & Core Workflow

๐Ÿ”น terraform version

Shows the installed version of Terraform and configured provider plugins.

terraform version

๐Ÿ”น terraform init

Initializes the working directory containing Terraform configuration files. Downloads required provider plugins and configures the backend.

# Standard initialization
terraform init

# Upgrade provider plugins to latest allowed versions
terraform init -upgrade

# Reconfigure backend settings (migrating state storage)
terraform init -reconfigure

๐Ÿ’ก Run this once per project after writing your .tf files or whenever you add new providers/modules.


๐Ÿ”น terraform fmt

Automatically rewrites Terraform configuration files to a canonical format and style.

# Format current directory
terraform fmt

# Format all files in subdirectories recursively
terraform fmt -recursive

# Check if files are formatted without modifying them (CI/CD check)
terraform fmt -check

๐Ÿ”น terraform validate

Validates your configuration files syntactically and checks whether internal references and arguments are valid without accessing remote services.

terraform validate

๐Ÿ”น terraform plan

Creates an execution plan, letting you preview what actions Terraform will take to reach the desired state before making changes.

# Preview changes
terraform plan

# Save the execution plan to a file (recommended for CI/CD)
terraform plan -out=tfplan

# Pass custom variable values via CLI
terraform plan -var="environment=production" -var="instance_count=3"

# Specify a custom variables file
terraform plan -var-file="prod.tfvars"

๐Ÿ“Œ Always run plan before apply to inspect additions (+), changes (~), and destructions (-).


๐Ÿ”น terraform apply

Executes the actions proposed in a Terraform plan to create, update, or delete infrastructure.

# Apply interactively (requires confirmation prompt)
terraform apply

# Auto-approve without prompt (useful in CI/CD pipelines)
terraform apply -auto-approve

# Apply a pre-generated plan file safely
terraform apply tfplan

๐Ÿ”น terraform destroy

Terminates all resources tracked by the current configuration and state.

# Destroy with confirmation prompt
terraform destroy

# Auto-confirm destruction
terraform destroy -auto-approve

# Preview destruction without deleting
terraform plan -destroy

๐ŸŸก Intermediate Commands & State Operations

๐Ÿ”น Modern Replacement for terraform taint (-replace)

[!WARNING] terraform taint is deprecated since Terraform v0.15.2 and v1.x. Use terraform apply -replace instead.

# Modern standard (Terraform 0.15.2+)
terraform apply -replace="aws_instance.example"

# Legacy command (retains for backwards compatibility)
terraform taint aws_instance.example
terraform untaint aws_instance.example

๐Ÿ”น terraform show

Displays human-readable output of the current state or a saved plan file.

# Show current state
terraform show

# Inspect a saved plan file
terraform show tfplan

# Output state in JSON for parsing with jq
terraform show -json

๐Ÿ”น terraform output

Extracts the values of output variables from the state file.

# List all outputs
terraform output

# Get a specific output
terraform output instance_ip

# Extract as raw string (strips quotes for scripting)
terraform output -raw instance_ip

# Output in JSON format
terraform output -json

๐Ÿ”น terraform state Management

Directly inspect and modify the Terraform state file.

# List all resources currently tracked in state
terraform state list

# Show detailed attributes of a tracked resource
terraform state show aws_instance.web

# Move/rename a resource within state without destroying it
terraform state mv aws_instance.old_name aws_instance.new_name

# Move resource into a module
terraform state mv aws_instance.web module.web_cluster.aws_instance.web

# Remove a resource from state without destroying it in the cloud
terraform state rm aws_instance.unmanaged_resource

# Pull remote state file to stdout
terraform state pull > backup.tfstate

๐Ÿ”น terraform workspace

Manages separate state instances within the same configuration directory (useful for multi-environment deployments like dev, staging, prod).

# List all workspaces
terraform workspace list

# Create a new workspace
terraform workspace new staging

# Switch between workspaces
terraform workspace select prod

# View current workspace
terraform workspace show

# Delete an empty workspace
terraform workspace delete staging

In HCL, reference the active workspace using ${terraform.workspace}:

locals {
  env = terraform.workspace
}

๐Ÿ”น terraform console

Launches an interactive shell for evaluating expressions, testing built-in functions, and inspecting variables.

terraform console
> max(5, 12, 9)
12
> format("web-%s-%02d", "prod", 1)
"web-prod-01"
> [for s in ["apple", "banana"] : upper(s)]
[
  "APPLE",
  "BANANA",
]
> exit

๐Ÿ”ด Advanced Concepts & Modern Features (Terraform 1.5 - 1.10+)

๐Ÿ”น Declarative import Blocks (Terraform 1.5+)

Terraform 1.5 introduced declarative imports in .tf code alongside automatic configuration generation.

# In imports.tf
import {
  to = aws_instance.web
  id = "i-0123456789abcdef0"
}

Generate configuration automatically:

# Generates the HCL resource block into generated.tf
terraform plan -generate-config-out=generated.tf

# Apply the generated import
terraform apply

Traditional CLI import:

terraform import aws_instance.web i-0123456789abcdef0

๐Ÿ”น Native Automated Testing (terraform test, 1.6+)

Terraform 1.6+ provides a built-in testing framework using .tftest.hcl files without external tools like Terratest.

# tests/website.tftest.hcl
variables {
  bucket_name = "test-company-static-website-dev"
}

run "validate_bucket_creation" {
  command = plan

  assert {
    condition     = aws_s3_bucket.website.bucket == var.bucket_name
    error_message = "S3 bucket name did not match expected variable"
  }
}

Run test suites:

terraform test
terraform test -verbose

๐Ÿ”น check Blocks (Continuous Validation, 1.5+)

Assert conditions in your infrastructure without failing the entire plan or apply:

check "health_check" {
  data "http" "website_status" {
    url = "https://${aws_lb.app.dns_name}/healthz"
  }

  assert {
    condition     = data.http.website_status.status_code == 200
    error_message = "${aws_lb.app.dns_name} returned non-200 status code."
  }
}

๐Ÿ”น Resource Lifecycle Meta-Arguments

Control how Terraform creates, updates, and deletes individual resources:

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"

  lifecycle {
    # Create replacement resource before destroying the existing one
    create_before_destroy = true

    # Prevent accidental terraform destroy
    prevent_destroy = false

    # Ignore cloud-side changes to specific attributes (e.g. auto-scaled tags)
    ignore_changes = [
      tags["LastUpdated"],
    ]

    # Replace resource when a specific trigger condition changes
    replace_triggered_by = [
      aws_security_group.web.id
    ]
  }
}

๐Ÿ”น for_each vs count

Featurecountfor_each
Identified ByIndex integer ([0], [1])Map key or string set (["web"], ["api"])
Shift RiskRemoving middle items causes recreation of subsequent itemsSafe removal; only the targeted key is destroyed
Use CaseIdentical copiesDistinct resources with unique names/keys
# Example with for_each:
variable "subnets" {
  type = map(string)
  default = {
    us-east-1a = "10.0.1.0/24"
    us-east-1b = "10.0.2.0/24"
  }
}

resource "aws_subnet" "main" {
  for_each          = var.subnets
  vpc_id            = aws_vpc.main.id
  availability_zone = each.key
  cidr_block        = each.value

  tags = {
    Name = "subnet-${each.key}"
  }
}

๐Ÿ”น dynamic Blocks

Generate nested configuration blocks dynamically from maps or lists:

variable "ingress_ports" {
  type    = list(number)
  default = [80, 443, 8080]
}

resource "aws_security_group" "web" {
  name = "web-sg"

  dynamic "ingress" {
    for_each = var.ingress_ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

๐Ÿ”น Remote Backend & State Locking (S3 + DynamoDB)

Store state files centrally with concurrency locking to prevent state corruption:

terraform {
  required_version = ">= 1.5.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket         = "my-company-terraform-state-prod"
    key            = "networking/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-lock"
  }
}

[!TIP] Terraform 1.10+ Native S3 Locking: Terraform 1.10+ supports native S3 conditional writes, allowing state locking directly on S3 without needing a DynamoDB table!


๐Ÿ”น Sensitive Values & Secret Protection

Mask passwords and credentials in CLI logs and plan outputs:

variable "db_password" {
  type      = string
  sensitive = true
}

output "database_url" {
  value     = "postgresql://admin:${var.db_password}@${aws_db_instance.main.endpoint}/app"
  sensitive = true
}

View sensitive output explicitly when needed:

terraform output -raw database_url

๐Ÿ›  Useful Environment Variables

VariableDescription
TF_LOG=TRACE|DEBUG|INFO|WARN|ERRORConfigures logging verbosity for debugging
TF_LOG_PATH=terraform.logWrites logs to a file instead of stdout
TF_VAR_name=valueSets variable values via shell environment
TF_CLI_ARGSAppends default arguments to all CLI commands
TF_IN_AUTOMATION=1Adjusts output formatting for automated CI/CD runs

๐Ÿง  Tips & Production Best Practices

  1. Protect Your State: Always use a remote backend (S3, GCS, Azure Blob, Terraform Cloud) with encryption enabled and state locking.
  2. Never Commit State Files or Secrets: Keep .tfstate, *.tfvars, and .terraform/ in .gitignore.
  3. Prefer for_each Over count: Using for_each prevents cascading resource recreation when list order changes.
  4. Pin Provider and Terraform Versions: Lock versions in required_providers and required_version to prevent breaking changes across team members.
  5. Enforce Modular Architecture: Split large monolithic configs into small, decoupled modules (e.g. networking, database, compute).
  6. Integrate Security Scanners in CI/CD: Run static analysis tools like checkov, tfsec, or trivy before terraform apply.

๐Ÿ“š Learning Resources

On this page

๐Ÿ“˜ Introduction๐Ÿ”น Key Concepts๐ŸŒ Terraform Commands Quick Reference๐Ÿ”น Check Version๐Ÿ”น Initialize Working Directory๐Ÿ”น Validate Configuration๐Ÿ”น Format Code๐Ÿ”น Show Help๐Ÿ”น Plan Infrastructure Changes๐Ÿ”น Apply Infrastructure Changes๐Ÿ”น Targeted Recreation (Modern Replacement for Taint)๐Ÿ”น Destroy Infrastructure๐Ÿ”น Output Variables๐Ÿ”น Manage State๐Ÿ”น Target Specific Resources๐Ÿ”น Work with Modules๐Ÿ”น Backend Configuration๐Ÿ”น Import Existing Infrastructure (CLI & Modern Import Block)๐Ÿ”น Native Automated Tests (Terraform 1.6+)๐Ÿ”น Graph Dependency Tree๐Ÿ”น Force Unlock State๐ŸŸข Beginner Commands & Core Workflow๐Ÿ”น terraform version๐Ÿ”น terraform init๐Ÿ”น terraform fmt๐Ÿ”น terraform validate๐Ÿ”น terraform plan๐Ÿ”น terraform apply๐Ÿ”น terraform destroy๐ŸŸก Intermediate Commands & State Operations๐Ÿ”น Modern Replacement for terraform taint (-replace)๐Ÿ”น terraform show๐Ÿ”น terraform output๐Ÿ”น terraform state Management๐Ÿ”น terraform workspace๐Ÿ”น terraform console๐Ÿ”ด Advanced Concepts & Modern Features (Terraform 1.5 - 1.10+)๐Ÿ”น Declarative import Blocks (Terraform 1.5+)๐Ÿ”น Native Automated Testing (terraform test, 1.6+)๐Ÿ”น check Blocks (Continuous Validation, 1.5+)๐Ÿ”น Resource Lifecycle Meta-Arguments๐Ÿ”น for_each vs count๐Ÿ”น dynamic Blocks๐Ÿ”น Remote Backend & State Locking (S3 + DynamoDB)๐Ÿ”น Sensitive Values & Secret Protection๐Ÿ›  Useful Environment Variables๐Ÿง  Tips & Production Best Practices๐Ÿ“š Learning Resources