Importing AWS Infrastructure to Terraform

Terraform is a great tool for setting up and configuring architecture as code. However, it can be tricky to manage resources that were not created by Terraform.

I recently worked on a project where most of our AWS infrastructure had been manually created in the AWS console. When we decided to manage all of our infrastructure via Terraform, it was easy to spin up new infrastructure for different environments, but not to manage the older infrastructure that had been created manually.

Fortunately, Terraform provides a way for you to import existing architecture into your project.

1. Create a Lambda

For this walkthrough, we are going to import an existing Lambda into our Terraform state. You can create a new Lambda or pick an existing one to use.

2. Set Up Terraform

Create a new Terraform file in an empty directory with the following contents:


provider "aws" {
  # access_key and secret_key can be excluded if you
  # have your creds setup in ~/.aws
  access_key = "ACCESS_KEY_HERE"
  secret_key = "SECRET_KEY_HERE"
  region = "us-east-1"
}

resource "aws_lambda_function" "terraform_lambda" {
  function_name = "terraform-managed-lambda"

  filename = "lambda.zip"

  handler = "index.handler"
  role    = "${aws_iam_role.iam_for_lambda.arn}"
  runtime = "nodejs8.10"
}

resource "aws_iam_role" "iam_for_lambda" {
  name = "iam_for_lambda"

  assume_role_policy = <<EOF

  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

In order to create a Lambda via Terraform, we need a zip of the Lambda to deploy. Open your Lambda in the AWS console, and select Actions > Export Function > Download deployment package. Download the file to the directory containing the Terraform file that you just created with the name lambda.zip.

Next, run terraform init and terraform plan. You should see that terraform wants to create a new Lambda and a new IAM role. Since we don’t want to create any new resources, let’s import our existing Lambda.

3. Import the Resource

To import a resource from AWS into Terraform, use the following command:

terraform import <terraform_resource_type>.<terraform_resource_name> <aws_resource_id>

In this example, we will run the following command:

terraform import aws_lambda_function.terraform_lambda name-of-your-lambda

This command will create a Terraform state file if needed and add the current state of your Lambda to it. Run terraform plan, and you will see that Terraform is now aware of your Lambda!

I hope this makes it easier to manage all of your infrastructure in Terraform.