Often users need to import resources into the HCP Terraform configuration which historically would rely on the Terraform import command.
The import command runs the import locally, so any variables in HCP Terraform required for authentication in the run would need to be copied locally or it errors:
terraform import aws_instance.ubuntu i-00000000000000000
╷
│ Error: No value for required variable
│
│ on /Users/user/my-workspace/main.tf line 40:
│ 40: variable "tfc_aws_dynamic_credentials" {
│
│ The root module input variable "tfc_aws_dynamic_credentials" is not set, and has no default value. Use a -var or -var-file command line argument to provide a value for this variable.
However, there may be scenarios where it is undesired to copy the variables to a local workspace or in this example when using dynamic credentials with multiple provider configurations.
This can be resolved by running the import through the HCP Terraform backend, where the variables reside, with an import block instead of the import command.
Prerequisites:
- HCP Terraform backend
- Dynamic Credentials configured
- Multiple Provider Configurations
- Resources to import
Here is an example of the Terraform import command:
terraform import aws_instance.ubuntu i-00000000000000000
Now instead of using that we want to create an import block within our configuration:
import {
to = aws_instance.ubuntu
id = "i-00000000000000000"
provider = aws.alias1
}
This requires 3 arguments if the default provider is not used:
to: The resource block that corresponds with the resource being imported
id: The id of the resource
provider: The alias to the desired provider configuration
To:
This represents the configuration for the resource. It should have the minimum required arguments needed. Following the aws_instance example:
resource "aws_instance" "ubuntu" {
provider = aws.alias1
ami = "ami-0124ee9682f33ad99"
instance_type = "t2.micro"
}
ID:
This depends on the resource and provider being used. Please refer to the provider documentation for the resource being imported for further details on the ID format that should be used.
Provider:
A provider argument to link the import to the corresponding provider via an alias. (the second provider configuration below)
provider "aws" {
region = "us-east-1"
shared_config_files = [var.tfc_aws_dynamic_credentials.default.shared_config_file]
}
provider "aws" {
alias = "alias1"
region = "us-west-1"
shared_config_files = [var.tfc_aws_dynamic_credentials.aliases["alias1"].shared_config_file]
}
Now with the above import block and corresponding resource block, a Terraform apply can be run which performs the import using the HCP Terraform backend rather than running locally. This allows the variables for authentication to be read and the import to complete.
Reference: