TerraformPilot

DevOps

Fix Terraform Error - Duplicate Resource Name

Fix duplicate resource name errors in Terraform. Handle resource address conflicts, module naming, moved blocks, and state surgery.

LLuca Berton1 min read

Quick Answer

#

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.

The Error

#
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.

What Causes This

#
  • Copy-paste mistake — duplicated a resource block and forgot to rename
  • Multiple files defining the same resource — Terraform loads all .tf files in a directory
  • Merging branches — two team members added the same resource name
  • Module collision — calling the same module twice without different names

How to Fix It

#

Solution 1: Rename the Duplicate

#
# ❌ Both named "web"
resource "aws_instance" "web" { ... }
resource "aws_instance" "web" { ... }  # ERROR
 
# ✅ Unique names
resource "aws_instance" "web" { ... }
resource "aws_instance" "api" { ... }

Solution 2: Use count or for_each

#
# 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 }
}

Solution 3: Move to a Module

#
# 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"
}

Solution 4: Find the Duplicate

#
# 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!

Troubleshooting Checklist

#
  1. ✅ Which files define the duplicate? (grep -rn)
  2. ✅ Is it a copy-paste error?
  3. ✅ Should these be count/for_each instead of separate blocks?
  4. ✅ Should one move to a module?
#

Conclusion

#

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.

#Terraform#Troubleshooting#DevOps#Error Fix#Infrastructure as Code

Share this article