0
0
TerraformHow-ToBeginner · 3 min read

How to Target Specific Resource in Terraform: Simple Guide

To target a specific resource in Terraform, use the -target option with the terraform apply or terraform plan commands followed by the resource address. This lets you apply changes only to that resource without affecting others.
📐

Syntax

The -target option is used with Terraform commands to specify the exact resource to act on. The syntax is:

  • terraform apply -target=<resource_address>
  • terraform plan -target=<resource_address>

Here, <resource_address> is the full name of the resource, including its type and name, like aws_instance.example.

bash
terraform apply -target=resource_type.resource_name
💻

Example

This example shows how to target a specific AWS EC2 instance resource named example in Terraform. It runs terraform apply only on that resource.

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

# Command to apply only this resource:
terraform apply -target=aws_instance.example
Output
Terraform will plan and apply changes only to the aws_instance.example resource, ignoring others.
⚠️

Common Pitfalls

Common mistakes when targeting resources include:

  • Using incomplete or incorrect resource addresses, causing Terraform to fail to find the resource.
  • Relying on -target for regular workflows, which can cause state inconsistencies.
  • Forgetting that dependencies of the targeted resource may not be updated, leading to errors.

Always use -target sparingly for debugging or emergency fixes, not for routine deployments.

bash
## Wrong usage (missing resource name):
terraform apply -target=aws_instance

## Correct usage:
terraform apply -target=aws_instance.example
📊

Quick Reference

OptionDescriptionExample
-targetSpecifies the resource to apply or planterraform apply -target=aws_instance.example
resource_addressFull resource type and nameaws_instance.example
UsageUse with apply or plan commandsterraform plan -target=aws_s3_bucket.mybucket

Key Takeaways

Use the -target option with terraform apply or plan to focus on a specific resource.
Specify the full resource address like resource_type.resource_name for targeting.
Avoid using -target for regular deployments to prevent state issues.
Check resource dependencies as they may not update automatically when targeting.
Use targeting mainly for debugging or emergency fixes.