Search code examples
amazon-web-serviceserror-handlingduplicatesterraformaws-security-group

Error creating Security Group: InvalidGroup.Duplicate when defining AWS security group in Terraform


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....


Solution

  • 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.