Terraform: Import AWS resources

Problem: Resource already exists

If there are some AWS resources that are not exist in terraform scripts and you run terraform apply, you might get “XXXX already exists” errors. I listed some of them:

BucketAlreadyExists: The requested bucket name is not available

EntityAlreadyExists: A policy called dummy-policy-name already exists. Duplicate names are not allowed

ResourceInUseException: Table already exists: dummy-table-name

DuplicateTargetGroupName: A target group with the same name ‘web-development-targetgroup’ exists, but with different settings

Resource alredy exists errors

Here is the error that I get in my current project.

 
module.xxxxxxxx.aws_iam_policy.policy: 1 error(s) occurred:
aws_iam_policy.policy: Error creating IAM policy XXXXXXXXXXXXDynamoDBPolicy: EntityAlreadyExists: A policy called
XXXXXXXXXXXXDynamoDBPolicy already exists. Duplicate names are not allowed.
status code: 409, request id: unique-id

Solution: Import existing modules

The terraform import command is used to import existing infrastructure. Importing can be done either specifying the Amazon Resource Name (ARN) format or the resource name. In theory, the format is as follows.

terraform import [options] ADDR IDD

Import using resource name

terraform import module.static-content-cloudfront.aws_s3_bucket.static_content my-s3-bucket

Import using ARN

terraform import module.webapp.aws_iam_policy.my_policy arn:aws:iam::229093002897:policy/my-development-policy

You can get the ARN with AWS console or using terraform show command

Get ARN with AWS Console

Get ARN using terraform show command

module.webapp.aws_iam_policy.my_policy:
id = arn:aws:iam::229093002897:policy/development-policy
arn = arn:aws:iam::229093002897:policy/development-policy
description =
name = development-policy
path = /
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": "ses:sendEmail",
"Resource": "*"
}
]
}

Leave a Reply

Your email address will not be published. Required fields are marked *