Terraform AWS Web Services DevOps
September 6, 2023
I heavily utilize AWS and Terraform in my daily work, and I recently encountered a situation where there was pre-existing infrastructure created manually in the AWS Management Console. I wanted to bring all of this infrastructure into Terraform to better manage it.
There are two primary methods for accomplishing this:
terraform import
commandTerraformer seems like a sane choice for this task. It simplifies the process of importing infrastructure into Terraform and offers a wide range of options. With Terraformer, you can import infrastructure from various cloud providers, including AWS, Azure, Google Cloud, Kubernetes, Alibaba Cloud, Oracle Cloud, and more. Furthermore, you have the flexibility to select specific resources to import, tailoring it to your needs.
To begin, create a new directory to house your Terraform code. I’ll create a directory called terraformer-test
in my home directory for this example.
mkdir terraformer-test
cd terraformer-test
Now, create a new file named main.tf
and include the following Terraform configuration:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.56.0"
}
}
}
provider "aws" {
# Replace the values with your own
profile = "xxx"
region = "xxx"
}
Next, initialize Terraform with the following command:
terraform init
This command will download the necessary Terraform provider, and your environment will be ready for Terraformer.
Before proceeding, ensure that you have Terraformer installed on your machine. You can find installation instructions in the official documentation.
Once Terraformer is installed, you can import your AWS infrastructure into Terraform using the following command:
terraformer import aws --resources=cloudfront
If everything goes smoothly, Terraformer will successfully import the infrastructure into Terraform. However, in my case, I encountered the following error:
No EC2 IMDS role found. Please make sure your instance has an IAM role attached with EC2 IMDS permissions.
I attempted to find a solution for this error but couldn’t find any helpful information, except for this GitHub issue, which was closed without a resolution.
Ultimately, here’s what worked for me:
AWS_ACCESS_KEY=xxx AWS_SECRET_KEY=xxx+T AWS_REGION=xxx AWS_PROFILE=xxx terraformer import aws --resources=cloudfront --profile=""
To resolve this issue, I had to set the following environment variables: AWS_ACCESS_KEY
, AWS_SECRET_KEY
, AWS_REGION
, and AWS_PROFILE
. Additionally, I set the --profile
option to an empty string. Following these adjustments, Terraformer was able to successfully import the infrastructure into Terraform.