Introduction
This article explains how to use the TF_CLI_ARGS_plan environment variable to target specific resources within an HCP Terraform or Terraform Enterprise run.
Use Case
Targeting specific resources is useful in exceptional scenarios, such as:
- When a partial apply leaves the state file in a condition that does not reflect reality.
- When you need to selectively destroy specific resources managed by Terraform.
- When nested
providerblocks are removed from within a module.
Procedure
Follow these steps to target resources in a remote run.
-
Identify the address of the resource you wish to target by listing the resources in your state file. You can target any resource listed in the output.
$ terraform state list null_resource.config module.database.null_resource.mysql module.database.null_resource.postgresql
- In your run's variable settings, create an environment variable named
TF_CLI_ARGS_planwith the value set to-target=<RESOURCE_ADDRESS>.-
To target a single resource: Set the value to
-target=null_resource.config. -
To target a resource within a module: Set the value to
-target=module.database.null_resource.mysql. -
To target all resources within a module: Set the value to
-target=module.database.
-
To target a single resource: Set the value to
Additional Information
Important Considerations
The -target option is not suitable for routine use. You should only use it in exceptional situations, such as recovering from configuration errors or when Terraform specifically suggests its use in an error message.
Using TF_CLI_ARGS_plan
This guide uses the TF_CLI_ARGS_plan environment variable instead of the more general TF_CLI_ARGS variable. This ensures the -target option applies only to the terraform plan command. This is necessary because HCP Terraform and Terraform Enterprise also run terraform show to generate Sentinel mocks, and the -target flag is not valid for the show command.