Fix Terraform Error: CloudWatch Log Group Already Exists
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
DevOps
How to fix InvalidGroup.Duplicate error when creating security groups in Terraform. Handle name conflicts and VPC-specific security groups.
Error creating Security Group: InvalidGroup.Duplicate: A security group with the same name already existsA 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.
# 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-0123456789abcdef0resource "aws_security_group" "web" {
name_prefix = "web-sg-" # Terraform adds a random suffix
vpc_id = aws_vpc.main.id
lifecycle {
create_before_destroy = true
}
}# 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 applyresource "aws_security_group" "web" {
name = "${var.project}-${var.environment}-web-sg"
description = "Security group for web servers"
vpc_id = aws_vpc.main.id
}terraform plan — always review before applyingterraform validate — catches syntax errors earlyLearn to avoid these errors with interactive, project-based courses:
Related: Fix the Terraform inconsistent dependency lock file error — quick fix for this common issue.
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.
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
Fix terraform import errors when a resource already exists in state. Covers state rm, state show, reimport workflow, import blocks
Fix terraform too many command line arguments errors. Correct -var syntax, quote values with spaces, and learn proper Terraform CLI argument format for plan
Fix terraform invalid escape sequence errors. Double backslashes for Windows paths, use heredocs for regex, and learn all valid HCL escape sequences.