'What is the best way to solve `EntityAlreadyExists` error in terraform?

I am using terraform v0.12.6 and I run into many errors like:

Error: Error creating Security Group: InvalidGroup.Duplicate: The security group 'security-search-populate' already exists for VPC 'vpc-003e06e33a87c22f5'
    status code: 400, request id: 82acdc81-c324-4672-b9fe-531eb8283ed3

Error: Error creating IAM Role PopulateTaskRole: EntityAlreadyExists: Role with name PopulateTaskRole already exists.
    status code: 409, request id: 49aac94c-d52b-11e9-a535-c19e5ed20660

I know I can resolve them by deleting these resources from AWS but I wonder whether there is a better solution?



Solution 1:[1]

If the existing resources are already in terraform in another module or workspace, then I would not import any of those resources since resources should be managed by a single state, not multiple.

If the existing resources are not managed anywhere else in terraform, then it should be imported into terraform.

You'll need to find the security group id of security-search-populate security group.

aws ec2 describe-security-groups \
    --group-names security-search-populate \
    --query 'SecurityGroups[].GroupId' \
    --output text

Let's say the sg id is sg-903004f8. Import security group to terraform resource aws_security_group.elb_sg using your dev profile.

AWS_PROFILE=dev terraform import aws_security_group.elb_sg sg-903004f8

To import IAM role PopulateTaskRole to terraform resource aws_iam_role.developer using your dev profile.

AWS_PROFILE=dev terraform import aws_iam_role.developer PopulateTaskRole

After these are imported, you can do a targeted terraform plan to see the differences between what's in source controlled terraform and what's upstream in AWS

AWS_PROFILE=dev terraform plan \
  -target aws_security_group.elb_sg \
  -target aws_iam_role.developer

Solution 2:[2]

Change property "name" to "name_prefix" solved to me, and doesn't duplicate any roles and/or policies.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 FvSoares