Table of Contents

The Error

Error: creating EC2 Instance: InvalidGroup.Duplicate / already exists

What Causes This

This error occurs when Terraform tries to create a resource that already exists in your cloud provider. Common causes: resources created manually in the console, a previous terraform apply partially succeeded, or state was lost/corrupted.

How to Fix It

Solution 1: Import the Existing Resource

# Terraform 1.5+ import block (recommended)
cat >> imports.tf << 'EOF'
import {
  to = aws_security_group.web
  id = "sg-0123456789abcdef0"
}
EOF

terraform plan -generate-config-out=generated.tf
terraform apply

Solution 2: Use terraform import (Legacy)

terraform import aws_instance.web i-0123456789abcdef0
terraform import aws_s3_bucket.data my-bucket-name
terraform import aws_security_group.web sg-0123456789abcdef0

Solution 3: Remove and Recreate

# If the existing resource can be deleted
# First, delete it from the cloud provider
aws ec2 terminate-instances --instance-ids i-0123456789abcdef0

# Then apply normally
terraform apply

Solution 4: Check for Name Conflicts

# Add random suffixes to avoid naming collisions
resource "random_id" "suffix" {
  byte_length = 4
}

resource "aws_s3_bucket" "data" {
  bucket = "my-app-data-${random_id.suffix.hex}"
}

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.