As described in our official documentation, resources can be imported into a stack. This article provides a quick-to-use configuration that allows you to import existing resources into a stack-based setup.
Expected Outcome
An existing resource is successfully imported into the Terraform state associated with a stack deployment.
Prerequisites
- An existing deployed stack in HCP Terraform
- If the stack is not already deployed, refer this document to deploy a stack first
Use Case
- Assume we already have a stack configured in HCP Terraform with the following directory structure:
├── components
│ └── microservice
│ ├── data.tf
│ ├── locals.tf
│ ├── main.tf
│ ├── variables.tf
│ └── import.tf
├── components.tfcomponent.hcl
├── deployments.tfdeploy.hcl
├── locals.tfdeploy.hcl
├── providers.tfcomponent.hcl
└── variables.tfcomponent.hcl- The component source is
./components/microservice - The stack has multiple deployments (for example,
devandprod) - Each deployment should import a different existing S3 bucket
Procedure:
We can define below configuration and push the code:
Deployment Configuration(deployments.tfdeploy.hcl): Define deployment-specific inputs:
deployment "dev" {
inputs = {
..
bucket_name = "<name-for-dev>"
..
}
}
deployment "prod" {
inputs = {
..
bucket_name = "<name-for-prod>"
..
}
}
Component Input Variable (variables.tfcomponent.hcl):Declare the variable that will be passed into the component:
variable "bucket_name" {
type = string
}
Component Definition (components.tfcomponent.hcl): Reference the component source and pass the deployment input:
component "instance" {
source = "./components/microservice"
inputs = {
bucket_name = var.bucket_name
# other inputs
}
}
Resource and Import Configuration(import.tf (inside ./components/microservice)): Define the resource and the import block:
variable "bucket_name" {}
resource "aws_s3_bucket" "example" {
bucket = var.bucket_name
}
import {
to = aws_s3_bucket.example
id = var.bucket_name
}
With this setup, you can reuse the same component while importing different S3 buckets per deployment by simply changing the bucket_name input in each environment (dev/prod).
Additional Information
- Managing resources in components:https://developer.hashicorp.com/terraform/language/stacks/component/manage#manage-resources
- Terraform import blocks: https://developer.hashicorp.com/terraform/language/import