Table of Contents

The Error

Error creating Security Group: InvalidGroup.Duplicate: A security group with the same name already exists

What Causes This

A security group with the same name already exists in the target VPC. Security group names must be unique within a VPC. This often happens when importing existing infrastructure or when a previous terraform destroy failed partially.

How to Fix It

Solution 1: Import the Existing Security Group

# Find the existing SG
aws ec2 describe-security-groups --filters "Name=group-name,Values=my-sg-name" \
  --query 'SecurityGroups[*].[GroupId,GroupName,VpcId]' --output table

# Import it
terraform import aws_security_group.web sg-0123456789abcdef0

Solution 2: Use name_prefix Instead of name

resource "aws_security_group" "web" {
  name_prefix = "web-sg-"  # Terraform adds a random suffix
  vpc_id      = aws_vpc.main.id

  lifecycle {
    create_before_destroy = true
  }
}

Solution 3: Delete the Duplicate

# Check if the SG is in use
aws ec2 describe-network-interfaces \
  --filters "Name=group-id,Values=sg-0123456789abcdef0" \
  --query 'NetworkInterfaces[*].NetworkInterfaceId'

# If not in use, delete it
aws ec2 delete-security-group --group-id sg-0123456789abcdef0

# Then apply
terraform apply

Solution 4: Use Unique Names

resource "aws_security_group" "web" {
  name        = "${var.project}-${var.environment}-web-sg"
  description = "Security group for web servers"
  vpc_id      = aws_vpc.main.id
}

Prevention Tips

  1. Pin provider versions — avoid surprise breaking changes
  2. Use CI/CD — catch errors before they hit production
  3. Test with terraform plan — always review before applying
  4. Keep Terraform updated — newer versions have better error messages
  5. Use terraform validate — catches syntax errors early

Hands-On Courses

Learn to avoid these errors with interactive, project-based courses:

Conclusion

This error is common and fixable. Follow the solutions above, and check our Terraform course for hands-on training that covers real-world troubleshooting scenarios.