Fix Terraform Error: CloudWatch Log Group Already Exists
Fix terraform CloudWatch Log Group ResourceAlreadyExistsException. Import orphaned log groups, prevent Lambda auto-creation
DevOps
Fix duplicate resource name errors in Terraform. Handle resource address conflicts, module naming, moved blocks, and state surgery.
Two resources in your configuration have the same type and name (e.g., two aws_instance "web" blocks). Rename one, move it to a module, or use count/for_each to create multiples from a single block.
Error: Duplicate resource "aws_instance" configuration
A resource "aws_instance" "web" was already declared at main.tf:15.
Resource names must be unique per type in a module..tf files in a directory# ❌ Both named "web"
resource "aws_instance" "web" { ... }
resource "aws_instance" "web" { ... } # ERROR
# ✅ Unique names
resource "aws_instance" "web" { ... }
resource "aws_instance" "api" { ... }# Instead of duplicating:
resource "aws_instance" "web" {
count = 3
ami = var.ami_id
instance_type = "t3.micro"
tags = { Name = "web-${count.index}" }
}
# Or with for_each for named instances:
resource "aws_instance" "app" {
for_each = toset(["web", "api", "worker"])
ami = var.ami_id
instance_type = "t3.micro"
tags = { Name = each.key }
}# modules/server/main.tf
resource "aws_instance" "this" {
ami = var.ami_id
instance_type = var.instance_type
tags = { Name = var.name }
}
# root main.tf
module "web" {
source = "./modules/server"
name = "web"
ami_id = var.ami_id
instance_type = "t3.micro"
}
module "api" {
source = "./modules/server"
name = "api"
ami_id = var.ami_id
instance_type = "t3.medium"
}# Search all .tf files for the duplicate resource
grep -rn 'resource "aws_instance" "web"' *.tf
# main.tf:15:resource "aws_instance" "web" {
# servers.tf:8:resource "aws_instance" "web" { ← duplicate!grep -rn)count/for_each instead of separate blocks?Resource names must be unique per type within a module. Use grep to find the duplicate, then either rename it, use count/for_each for multiples, or extract into a module. Terraform loads all .tf files in a directory, so check every file.
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.