Fix Terraform Error: CloudWatch Log Group Already Exists
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
DevOps
Fix terraform duplicate resource definition errors. Find duplicates across .tf files, rename resources, use count/for_each for multiples
# Find the duplicate
grep -rn 'resource "aws_instance" "web"' *.tf
# Rename one of them to a unique nameError: Duplicate resource "aws_instance" configuration
on ec2.tf line 15:
15: resource "aws_instance" "web" {
A aws_instance resource named "web" was already declared at main.tf:10,1-32.
Resource names must be unique per type in a module.main.tf and ec2.tf both have resource "aws_instance" "web"# Search across all .tf files
grep -rn 'resource "aws_instance" "web"' .
# Find ALL duplicate resource declarations
grep -rh 'resource "' *.tf | sort | uniq -d./main.tf:10:resource "aws_instance" "web" {
./ec2.tf:15:resource "aws_instance" "web" { ← Duplicate!# main.tf
resource "aws_instance" "web_primary" {
# ...
}
# ec2.tf
resource "aws_instance" "web_secondary" {
# ...
}If the resource already exists in state, use terraform state mv:
terraform state mv aws_instance.web aws_instance.web_primaryIf you need multiple identical resources:
# Instead of two separate blocks:
resource "aws_instance" "web" {
count = 2
ami = var.ami_id
instance_type = "t3.micro"
tags = {
Name = "web-${count.index}"
}
}Or with for_each for named instances:
resource "aws_instance" "web" {
for_each = toset(["primary", "secondary"])
ami = var.ami_id
instance_type = "t3.micro"
tags = {
Name = "web-${each.key}"
}
}If resources grew organically across files:
# Before (messy, prone to duplicates)
main.tf ← has aws_instance "web"
ec2.tf ← also has aws_instance "web" 💥
# After (organized)
modules/web/
├── main.tf ← aws_instance "this"
└── variables.tf
main.tf ← module "web" { source = "./modules/web" }# Validate catches duplicates
terraform validate
# Format and check before commit
terraform fmt -check -recursive
# Pre-commit hook
#!/bin/bash
terraform validate || exit 1
terraform fmt -check -recursive || exit 1Duplicate resource names must be unique per type within a module. Find duplicates with grep, rename one, and use terraform state mv if the resource already exists. For multiple similar resources, use count or for_each instead of separate blocks.
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.