0
0
TerraformHow-ToBeginner · 3 min read

How to Use -target in Terraform: Syntax and Examples

Use the -target option with terraform plan or terraform apply to focus on specific resources by their address. This lets you apply or plan changes only for those resources without affecting the entire infrastructure.
📐

Syntax

The -target option is used with Terraform commands like plan or apply to specify which resource(s) to focus on. You provide the resource address after -target=.

  • terraform plan -target=resource_address: Shows the plan for the targeted resource only.
  • terraform apply -target=resource_address: Applies changes only to the targeted resource.

The resource_address is the full name of the resource, including its type and name, for example aws_instance.example.

bash
terraform plan -target=aws_instance.example
terraform apply -target=aws_instance.example
💻

Example

This example shows how to use -target to apply changes only to a specific AWS instance resource named aws_instance.example without affecting other resources.

hcl
provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

resource "aws_s3_bucket" "bucket" {
  bucket = "my-unique-bucket-12345"
  acl    = "private"
}

# Run this command to apply only the aws_instance.example resource
# terraform apply -target=aws_instance.example
Output
Terraform will apply changes only to the aws_instance.example resource, leaving aws_s3_bucket.bucket unchanged.
⚠️

Common Pitfalls

  • Partial state updates: Using -target can cause Terraform to skip dependencies, leading to inconsistent state.
  • Not a long-term solution: -target is meant for temporary use, not regular workflows.
  • Forgetting resource address: The full resource address must be exact, including module paths if used.

Example of a wrong and right usage:

bash
# Wrong: Missing full resource address or typo
terraform apply -target=aws_instance

# Right: Full resource address
terraform apply -target=aws_instance.example
📊

Quick Reference

OptionDescription
-target=resource_addressFocus plan or apply on specific resource only
terraform plan -target=...Show changes for targeted resource
terraform apply -target=...Apply changes only to targeted resource
Use full resource addressInclude module names if resource is inside modules
Temporary use onlyAvoid using -target for regular deployments

Key Takeaways

Use -target with terraform plan or apply to focus on specific resources.
Always specify the full resource address including module paths if any.
-target is for temporary, selective changes, not regular workflows.
Be careful of dependency issues when targeting resources.
Check your resource addresses carefully to avoid errors.