0
0
TerraformHow-ToBeginner · 4 min read

How to Import Existing Resource to Terraform State Easily

To import an existing resource into Terraform state, use the terraform import command followed by the resource address and the resource ID. This links the existing resource to your Terraform configuration without recreating it.
📐

Syntax

The terraform import command requires two main parts:

  • Resource address: The name you gave the resource in your Terraform code, like aws_instance.myserver.
  • Resource ID: The unique identifier of the existing resource in the cloud provider, like an instance ID.

The full command looks like this:

bash
terraform import <resource_address> <resource_id>
💻

Example

This example shows how to import an existing AWS EC2 instance into Terraform state. First, define the resource in your Terraform file, then run the import command with the instance ID.

hcl
provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "myserver" {
  # Configuration will be filled after import
}

# Run this command in terminal:
# terraform import aws_instance.myserver i-0abcd1234efgh5678
Output
aws_instance.myserver: Importing from ID "i-0abcd1234efgh5678"... aws_instance.myserver: Import prepared! Prepared aws_instance for import aws_instance.myserver: Refreshing state... [id=i-0abcd1234efgh5678] Import successful!
⚠️

Common Pitfalls

  • Missing resource block: You must have the resource defined in your Terraform code before importing.
  • Wrong resource address: The address must match exactly the resource name and type in your code.
  • Incorrect resource ID: Use the exact ID from your cloud provider; otherwise, import will fail.
  • State conflicts: Avoid importing resources already managed by Terraform to prevent state conflicts.
bash
## Wrong way: Importing without resource defined
terraform import aws_instance.myserver i-0abcd1234efgh5678

## Right way: Define resource first
resource "aws_instance" "myserver" {}
terraform import aws_instance.myserver i-0abcd1234efgh5678
📊

Quick Reference

StepDescription
1. Define resourceAdd the resource block in your Terraform configuration.
2. Find resource IDGet the unique ID of the existing resource from your cloud provider.
3. Run importUse terraform import resource_address resource_id command.
4. Verify stateRun terraform plan to check the imported resource state.
5. Update configAdd any missing configuration to match the imported resource.

Key Takeaways

Always define the resource in Terraform code before importing.
Use the exact resource address and cloud provider ID in the import command.
Importing links existing resources to Terraform state without recreating them.
Check your Terraform state and plan after import to ensure correctness.
Avoid importing resources already managed by Terraform to prevent conflicts.