How to target resources on Terraform
When you run terraform apply without any flags, Terraform applies all the changes in your plan at once. If you’ve ever worked on a large Terraform project, you know how overwhelming that can get. Sometimes you just want to apply one specific change without touching everything else. That’s where the -target flag comes in.
How to target specific resources
Terraform compares your configuration against the current state of your infrastructure and builds a plan showing all the differences. When you apply, Terraform creates, modifies, or destroys resources based on that plan.
There are times when the state drifts out of sync with your actual infrastructure – maybe a network issue, a provider bug, or something on the cloud side went wrong. In those cases, you might not want to apply the entire plan. You can use -target to focus on just the resource you need to fix.
The first step is finding the resource address in your state.
Run this command:
terraform state list
Let’s say you want to apply changes only for a specific Lambda function. After running terraform state list, you find the address:
aws_lambda_function.msk_rotation_lambda_function
To apply only that resource:
terraform apply -target="aws_lambda_function.msk_rotation_lambda_function"
The -target flag also works with terraform plan and terraform destroy.
How to target a module
You can use -target to select entire modules too. Once you have the module address from terraform state list, you can target it directly.
For example:
terraform plan -target=module.eks-cluster
This targets everything inside that module.
When targeting causes problems
There’s one scenario where you should think twice before using -target. Imagine your project creates an AWS EFS volume, but the EFS name is generated by a random resource like random_pet. You also have a Terraform output that prints that name.
If you target just the random_pet resource to generate a new name, Terraform’s state becomes unreliable. The output might reflect the new random value, but Terraform won’t actually recreate the EFS with that new name. You’re mixing targeted state changes with your actual infrastructure, and they can get out of step.
Conclusion
The -target flag is useful when you need to troubleshoot or fix a specific resource without touching the rest of your infrastructure. But it’s not something you should make a habit of – applying changes selectively can leave your state and actual infrastructure out of alignment.
Comments