Terraform Config-Driven Import: Bring Your Infrastructure Under Control
Why Import Resources into Terraform?
When managing existing infrastructure with Terraform, importing resources is often the first step. It helps bring unmanaged resources into Terraform’s control so you can automate and standardize their management. Terraform 1.5 introduces Config-Driven Import, a game-changer that simplifies and secures this process.
What’s New in Config-Driven Import?
Previously, Terraform's import
command had some challenges:
One at a time: Resources had to be imported individually.
Risky state changes: The state file was modified immediately, sometimes causing unintended changes.
Manual code writing: Resource blocks had to be written manually.
Terraform 1.5 solves these issues with:
Bulk import: Import multiple resources in one go.
Plan-first workflow: Preview imports before they modify the state.
Automatic code generation: Save time with ready-made resource blocks.
How Does Config-Driven Import Work?
Add Import Blocks:
Use the newimport
block to declare resources to import. Each block specifies:The ID of the resource (from the cloud provider).
The Terraform resource address (
to
field), which indicates the logical name and type of the resource in your configuration.
Example for an AWS EC2 instance:
import {
id = "i-abc123"
to = aws_instance.my_instance
}
Run the Plan:
Use the-generate-config-out
option to preview the import and generate resource blocks:terraform plan -generate-config-out=generated_resources.tf
Review and Apply:
Review the generated file (
generated_
resources.tf
).Run
terraform apply
to complete the import safely.
Why Is It Safer and Faster?
No manual edits: The resource code is auto-generated.
State safety: No accidental state changes since everything is previewed first.
Bulk imports: Import dozens of resources in one go.
Terraform Cloud support: No need for local credentials or direct access to the state file.
Enhanced Validation with Check Blocks
Terraform 1.5 also introduces Check Blocks for validating your infrastructure.
What are Check Blocks?
Check blocks ensure that the provisioned infrastructure works as expected. Unlike resource-level conditions, checks validate the overall functionality.Example:
check "health_check" { data "http" "example" { url = "https://${aws_lb.example.dns_name}" } assert { condition = data.http.example.status_code == 200 error_message = "Web application is unhealthy!" } }
When to Use Them?
Use checks to ensure your infrastructure is healthy after it’s deployed.
Why Upgrade to Terraform 1.5?
With config-driven imports and check blocks, Terraform 1.5 makes managing infrastructure easier, safer, and faster.
Save time with auto-generated code.
Avoid risks with planned imports.
Validate infrastructure with powerful checks.