0
0
TerraformHow-ToBeginner · 3 min read

How to Use Terraform Import: Syntax, Example, and Tips

Use terraform import <resource_type>.<resource_name> <resource_id> to bring existing infrastructure into Terraform state. This command links real resources to your Terraform configuration so you can manage them with Terraform.
📐

Syntax

The basic syntax of terraform import is:

  • terraform import: The command to import resources.
  • <resource_type>.<resource_name>: The Terraform resource address defined in your configuration.
  • <resource_id>: The ID of the existing resource in the cloud or provider.
bash
terraform import <resource_type>.<resource_name> <resource_id>
💻

Example

This example imports an existing AWS S3 bucket named my-bucket into Terraform state. You must have a matching resource block in your Terraform code.

hcl
resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"
  acl    = "private"
}

# Import command to run in terminal:
terraform import aws_s3_bucket.my_bucket my-bucket
Output
aws_s3_bucket.my_bucket: Importing from ID "my-bucket"... aws_s3_bucket.my_bucket: Import prepared! Prepared aws_s3_bucket for import aws_s3_bucket.my_bucket: Refreshing state... [id=my-bucket] Import successful! The resources that were imported are now in your Terraform state and can be managed.
⚠️

Common Pitfalls

Common mistakes when using terraform import include:

  • Not having a matching resource block in your Terraform code before importing.
  • Using the wrong resource ID format for the provider.
  • Expecting import to create configuration; it only updates state.
  • Forgetting to run terraform plan after import to verify state matches configuration.
bash
## Wrong: Importing without resource block
terraform import aws_s3_bucket.my_bucket my-bucket

## Right: Define resource first, then import
resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"
  acl    = "private"
}
terraform import aws_s3_bucket.my_bucket my-bucket
📊

Quick Reference

CommandDescription
terraform import . Import existing resource into Terraform state
terraform planCheck if imported state matches configuration
terraform state listList resources in Terraform state
terraform state show Show details of imported resource state

Key Takeaways

Always define the resource block in Terraform before running terraform import.
Use the exact resource ID required by the cloud provider when importing.
terraform import updates state only; it does not create configuration code.
Run terraform plan after import to verify the imported resource matches your config.
Common errors come from missing resource blocks or incorrect resource IDs.