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.
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.terraform refresh
to ensure the imported resource is fully aligned with its actual state.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.
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.
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.