Terraform CLI Commands
The Terraform CLI is the primary interface for working with infrastructure code. Understanding each command’s purpose, key flags, and when to use them is essential for both day-to-day work and DevOps interviews.
Core Workflow Commands
terraform init
Initializes the working directory — downloads providers, sets up the backend, and prepares modules.
terraform init # Standard initializationterraform init -upgrade # Upgrade providers within constraintsterraform init -backend=false # Skip backend configuration (local testing)terraform init -reconfigure # Force backend reconfigurationterraform init -backend-config="bucket=my-state-bucket" # Override backend settingsRun init whenever:
- Starting a new project
- Adding/changing providers
- Changing backend configuration
- After cloning a repo
terraform validate
Checks syntax and internal consistency without accessing any remote APIs.
terraform validate # Validate current directoryterraform validate -json # Machine-readable JSON output (for CI)validate catches: missing required arguments, type mismatches, invalid references. It does NOT catch: API-side errors (wrong AMI ID, insufficient permissions).
terraform fmt
Automatically formats .tf files to canonical HCL style.
terraform fmt # Format current directoryterraform fmt -recursive # Format all subdirectories tooterraform fmt -check # Exit 1 if files need formatting (use in CI)terraform fmt -diff # Show diff of changesAdd terraform fmt -check -recursive to your CI pipeline to enforce consistent formatting.
terraform plan
Creates an execution plan showing what changes will be made.
terraform plan # Basic planterraform plan -out=tfplan # Save plan to file (use with apply)terraform plan -var="environment=prod" # Override a variableterraform plan -var-file="prod.tfvars" # Use a specific vars fileterraform plan -target=aws_instance.web # Plan only specific resourceterraform plan -destroy # Show what destroy would removeterraform plan -refresh=false # Skip state refresh (faster, less safe)terraform plan -compact-warnings # Summarize warningsThe output symbols:
+Resource will be created-Resource will be destroyed~Resource will be updated in-place-/+Resource will be destroyed and recreated
terraform apply
Applies changes to reach the desired state.
terraform apply # Show plan, prompt for confirmationterraform apply -auto-approve # Skip confirmation (use in CI/CD only)terraform apply tfplan # Apply a saved plan file (no re-plan)terraform apply -var="env=prod" # Override variableterraform apply -target=aws_s3_bucket.logs # Apply only one resourceterraform apply -parallelism=20 # Concurrent operations (default: 10)Best practice for production: terraform plan -out=tfplan && terraform apply tfplan. This guarantees what you reviewed is exactly what gets applied.
terraform destroy
Destroys all resources managed by the configuration.
terraform destroy # Prompt for confirmationterraform destroy -auto-approve # No confirmation (use with extreme care)terraform destroy -target=aws_instance.old # Destroy a specific resource onlyState Management Commands
terraform show
Displays current state or a saved plan.
terraform show # Show current stateterraform show tfplan # Show saved plan contentsterraform show -json | jq '.values' # Parse state as JSONterraform state
Directly inspect and manipulate the state file.
terraform state list # List all managed resourcesterraform state show aws_instance.web # Details of one resourceterraform state mv aws_instance.old aws_instance.new # Rename resource in stateterraform state rm aws_instance.web # Remove from state (doesn't delete real resource)terraform state pull # Download remote state to stdoutterraform state push terraform.tfstate # Upload local state to backendterraform import
Import existing infrastructure into Terraform state.
terraform import aws_s3_bucket.existing my-existing-bucketterraform import aws_instance.server i-1234567890abcdef0Utility Commands
terraform output
Read outputs after apply.
terraform output # All outputsterraform output vpc_id # Specific outputterraform output -json # JSON format (for scripting)terraform output -raw load_balancer_dns # Raw string (no quotes)terraform console
Interactive REPL for evaluating expressions.
terraform console> cidrsubnet("10.0.0.0/16", 8, 1)"10.0.1.0/24"> length(["a", "b", "c"])3> var.environment"production"terraform workspace
Manage named workspaces for state isolation.
terraform workspace list # List workspacesterraform workspace new staging # Create and switch to stagingterraform workspace select production # Switch workspaceterraform workspace show # Current workspace nameterraform workspace delete staging # Delete a workspaceterraform graph
Outputs the dependency graph in DOT format.
terraform graph | dot -Tsvg > graph.svg # Visualize with GraphvizFrequently Used Flags Cheat Sheet
| Flag | Commands | Purpose |
|---|---|---|
-auto-approve | apply, destroy | Skip interactive confirmation |
-var="key=val" | plan, apply | Override a single variable |
-var-file=file | plan, apply | Load variables from file |
-target=resource | plan, apply, destroy | Limit to specific resource |
-out=file | plan | Save plan for later apply |
-refresh=false | plan, apply | Skip state refresh |
-lock=false | plan, apply | Disable state locking (caution) |
-compact-warnings | plan, apply | Suppress verbose warnings |
-json | plan, apply, show | JSON output for tooling |
CI/CD-Friendly Workflow
# In CI pipelines — non-interactive, explicit, auditableterraform init -input=falseterraform validateterraform fmt -check -recursiveterraform plan -out=tfplan -input=falseterraform apply -input=false tfplanThe -input=false flag causes Terraform to fail rather than prompt for user input, which is the correct behavior in automated pipelines.