Introduction
This article details how to use the TF_CLI_ARGS_plan environment variable to target resources within a Terraform Enterprise/Cloud run.
Use Case
Targeting specific resources is useful in the following scenarios.
-
When Terraform performed a partial apply, leaving the state file in a condition where it does not reflect reality.
-
When selectively destroying resources managed by Terraform.
-
When nested
providerblocks are removed from within a module.
Procedure
Any resource listed in terraform state list can be targeted.
Given the following output of terraform state list:
null_resource.config
module.database.null_resource.mysql
module.database.null_resource.postgresql
The null_resource.config resource can be targeted by creating an environment variable named TF_CLI_ARGS_plan with the value -target=null_resource.config.
The module.database.null_resource.mysql resource can be targeted by creating an environment variable named TF_CLI_ARGS_plan with the value -target=module.database.null_resource.mysql.
All resources within thedatabase module can be targeted by creating an environment variable named TF_CLI_ARGS_plan with the value -target=module.database.
Additional Information
Note that the -target option is not suitable for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error message.
The TF_CLI_ARGS_plan environment variable is used instead of the TF_CLI_ARGS environment variable to ensure the -target option only applies to terraform plan. This is necessary since Terraform Cloud and Terraform Enterprise run terraform show to generate Sentinel mocks.