• Blog
  • Import Existing AWS Resources with Terraform

Import Existing AWS Resources with Terraform

Josh Pollara
Josh Pollara

While Terraform is a powerful and effective tool to manage cloud resources, it is oftentimes not uncommon to discover various pieces of existing infrastructure created via cloud provider UI consoles. This can easily cause drift in your Terraform state. Terraform comes with the import subcommand to import existing resources into Terraform state.

In this blog post, I'll share how to successfully import a manually created AWS EC2 instance to a Terraform state file and generate the associated HCL.

The first step of our process is to create the Terraform HCL for our manually created resources. You can use the AWS Console or AWS CLI to obtain the instance ID of the resource. Once the instance ID is known, the HCL can be created for the AWS instance:

resource "aws_instance" "example" {
  # resource configuration

You are now ready to attach your new HCL to your Terraform state using the instance id:

$ terraform import aws_instance.example: i-abcd1234

The above command writes the AWS EC2 resource to your Terraform state. To validate the configuration with the imported resource, you can run a terraform plan. This gives you a pathway to match your HCL to your existing EC2 insance configuration that was created outside of Terraform.

Similarly, if you want to import an AWS S3 resource, you would take the same steps.

Create your HCL for the resource:

resource "aws_s3_bucket" "example" {
  # resource configuration

Attach the existing resource to your Terraform state:

$ terraform import aws_s3_bucket.example example

If you have many resources to be imported, this can be a tedious process. In a future post I'll give some tips and tricks on how to import an entire AWS account into a fresh Terraform repository using Terrateam.