Blog post

Import Existing AWS Resources with Terraform

2022-05-28

4 minute read

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:

1resource "aws_instance" "example" {
2  # resource configuration
3}
4

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

1terraform import aws_instance.example: i-abcd1234
2

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:

1resource "aws_s3_bucket" "example" {
2  # resource configuration
3}
4

Attach the existing resource to your Terraform state:

1terraform import aws_s3_bucket.example example
2

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.

GitHub App Install to Terraform Apply 🚀