6

I'm new to Terraform, when I run Terraform apply, I git this error:

Error: Error creating Security Group: InvalidGroup.Duplicate: The security group 'xxxxxxx' already exists for VPC 'vpc-xxxxxx'
        status code: 400

The script for this part looks like this:

resource "aws_security_group" "xxxxx_security_group" {
  name   = "xxxxx-security-group-xxxx"
  vpc_id = xxxxxxxxxxxxx

  egress {
    from_port   = x
    protocol    = x
    to_port     = x
    cidr_blocks = ["x.x.x.x/x"]
  }
}

Can someone give me some hints? Spent like almost an hour now, still no clue....

wawawa
  • 2,835
  • 6
  • 44
  • 105

1 Answers1

9

It looks like you created the security group in the console already (or with the CLI), so trying to create the security group again in terraform is causing an error because the name already exists.

To fix this, go into the AWS console and look for the security group with the name you're trying to make. Find its ID value, which will look like sg-xxxxxxxxxxxx.

Then in your terminal, import that resource into your terraform state by running:

terraform import aws_security_group.xxxxx_security_group sg-xxxxxxxxxxx

After this, you can run terraform plan or terraform apply and everything should work, because terraform's state knows about the existing resource.

David Mattia
  • 409
  • 4
  • 5
  • 1
    I think it's worth noting that after that `terraform import` command succeeds Terraform will believe it is the only thing managing that object, and so e.g. if you subsequently run `terraform destroy` then Terraform will plan to destroy it. Should be sure that you really want to manage an object with Terraform before importing. – Martin Atkins Feb 14 '20 at 17:39
  • 2
    Hi thanks, but I still have two questions: 1. My existing security group shows it's managed by Terraform already, is this method still working? 2.The command you mentioned ```aws_security_group.xxxxx_security_group```, is```xxxxx``` the full name of my security group? – wawawa Feb 17 '20 at 09:13
  • This should be a bug in terraform except if you are using `lifecycle { create_before_destroy = true }` for the resource. TF should simply destroy the existing resource and create a new one as you told it to do so. You can also use `name_prefix` instead of `name` for your resource to avoid name conflicts. – IgorC Nov 10 '21 at 02:55
  • I have also seen this behavior when people run `apply` without running a `plan` stage first in a CICD pipelines. – IgorC Nov 10 '21 at 03:11