Terrafrom Import

Infrastructure often exists before Terraform is introduced to manage it. Whether it’s an EC2 instance, a database, or a network, the terraform import command allows you to bring existing resources under Terraform’s control. This seamless integration ensures your state file reflects the current infrastructure without disrupting the live environment.

Why Use terraform import?

  • To manage manually created or pre-existing resources using Terraform.
  • To bring unmanaged resources into Terraform’s state file.
  • To avoid rebuilding or recreating infrastructure just to add it to Terraform.

How to Use It?

  • To import a resource: Use terraform import <resource_name> <resource_id>. Replace <resource_name> with the resource definition in your configuration and <resource_id> with the unique identifier of the resource in the cloud provider.
  • To refresh the state after importing: Run terraform refresh to ensure the imported resource is fully aligned with its actual state.

Example: Importing an EC2 Instance

Suppose you have an existing AWS EC2 instance with the ID i-0abcd1234efgh5678. You want to manage it with Terraform. First, add a matching resource block to your configuration file, main.tf:

resource "aws_instance" "example" {
  # No properties defined yet; this will be populated after import
}

Next, run the terraform import command:

terraform import aws_instance.example i-0abcd1234efgh5678

The output confirms the import:

aws_instance.example: Importing from ID "i-0abcd1234efgh5678"...
aws_instance.example: Import complete

Now, the EC2 instance is part of your Terraform state file. You can run terraform plan to view its details and add additional properties in your configuration.

Use Case

Imagine you’re adopting Terraform to manage an existing cloud environment, but rebuilding everything is impractical. With terraform import, you can bring resources under Terraform’s management incrementally, allowing for a smooth transition.

Conclusion

The terraform import command is a powerful tool for integrating existing resources into your Terraform-managed infrastructure. By using it effectively, you can unify your infrastructure under Terraform’s control without risking downtime or disruptions.