How to import existing infrastructure into Terraform?

There are many instances where you may create cloud infrastructure manually and later regret that decision, wondering why you did not use an Infrastructure as Code (IAC) tool like Terraform in the first place. At times you may inherit some legacy cloud architecture for which you would like to use IAC now.

In this article, I’ll show you how to import existing infrastructure into Terraform so that you can manage it like any other Terraform-managed infrastructure. We’ll be taking an example of AWS cloud.

Sanjeet Mehta
Sanjeet Kumar

April 20, 2023 | 5 minutes read

What is terraform?

Terraform is a popular Infrastructure as Code (IAC) tool that enables you to define and manage cloud infrastructure in a declarative way. With Terraform, you can define your infrastructure as code using a simple and easy-to-read language, which makes it easy to version, collaborate, and audit your infrastructure changes.

Terraform Import

The terraform import command is a Terraform CLI command that allows you to import existing infrastructure resources into your Terraform state. When you import a resource, Terraform will create a resource state for it and add it to your Terraform state file.

Before you run terraform import you must manually write a resource configuration block for the resource. The resource block describes where Terraform should map the imported object. (https://developer.hashicorp.com/terraform/cli/import#terraform-cloud)

The terraform import command takes two arguments:

Here is the syntax for the terraform import command:

 
terraform import <Terraform_resource_address> <resource_identifier>

For example, if you want to import an existing AWS EC2 instance with the ID i-0123456789abcdef0 into a Terraform aws_instance resource block named example, you would run the following command:

 
resource "aws_instance" "example" {
  instance_id = "i-0123456789abcdef0"
}

 
terraform import aws_instance.example i-0123456789abcdef0

 
Before you run terraform import you must manually write a resource 
configuration block for the resource. The resource block describes 
where Terraform should map the imported object.

Terraformer

How does terraformer solve our problem?

  1. Terraformer helps you to create a resource configuration block by importing the resources and its configuration.

     
    terraformer import aws --resources=ec2_instance --filter=id=i-0123456789abcdef0
    
    
  2. The output of the above command is a terraform resource block looking like this:

     
    resource "aws_instance" "tfer--i-0123456789abcdef0" {
      instance_id = "i-0123456789abcdef0"
    ....rest of the configuration
    }
    
    
  3. Now you can use the terraform import command to track this block via terraform

     
    terraform import aws_instance.tfer--i-0123456789abcdef0 i-0123456789abcdef0