Targetting resources in terraform is selecting and applying changes to specific resources within your Terraform configuration. This feature is used to control which resources are created, modified, or destroyed
Prerequisites:
- Install Terraform - here
Targeting Syntax
terraform <command> -target=<resource-type>.<resource-name>
Example of terrafom apply command targeting aws_instance.example
resource
terraform apply -target=aws_instance.example
Example usage:
Example terraform code:
resource "aws_s3_bucket" "a" {
bucket = "example-bucket-1a"
}
resource "aws_s3_bucket" "b" {
bucket = "example-bucket-2b"
}
While running terraform apply
we would create both buckets:
Terraform will perform the following actions:
# aws_s3_bucket.a will be created
+ resource "aws_s3_bucket" "a" {
+ acceleration_status = (known after apply)
+ acl = (known after apply)
.....
Plan: 2 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
After apply finished, let's destroy "aws_s3_bucket" "b"
, while keeping "aws_s3_bucket" "a"
. Run:
terraform destroy --target aws_s3_bucket.b
After destroy finished we can see that bucket 1a is still running:
$aws s3 ls
2023-10-20 12:23:09 example-bucket-1a
Now lets add another bucket to the code:
resource "aws_s3_bucket" "a" {
bucket = "example-bucket-1a"
}
resource "aws_s3_bucket" "b" {
bucket = "example-bucket-2b"
}
resource "aws_s3_bucket" "c" {
bucket = "example-bucket-3c"
}
We would target resource aws_s3_bucket.c
:
terraform apply --target aws_s3_bucket.c
As expected, we can see now 2 buckets running:
aws s3 ls
2023-10-20 12:23:09 example-bucket-1a
2023-10-20 12:30:53 example-bucket-3c
There is a CLI Tool which makes it easier to target terraform resources. You can find more about it here