Table of Contents

The Error

A resource "aws_instance" "web" was already declared

What Causes This

Two resource blocks have the same type and name in your configuration. This can happen when merging branches, copying files, or when multiple .tf files define the same resource.

How to Fix It

Solution 1: Find Duplicates

# Search all .tf files for the duplicate resource
grep -rn 'resource "aws_instance" "web"' *.tf modules/

# Check for duplicate files
find . -name "*.tf" | xargs grep -l 'resource "aws_instance" "web"'

Solution 2: Rename One Resource

# Before — both called "web"
resource "aws_instance" "web" { ... }  # in main.tf
resource "aws_instance" "web" { ... }  # in servers.tf

# After — unique names
resource "aws_instance" "web_frontend" { ... }
resource "aws_instance" "web_backend" { ... }

Solution 3: Use count or for_each

# Instead of multiple blocks
resource "aws_instance" "web" {
  count         = 3
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  tags = {
    Name = "web-${count.index + 1}"
  }
}

Solution 4: Move to Modules

# Separate into modules for organization
module "frontend" {
  source        = "./modules/server"
  name          = "frontend"
  instance_type = "t3.small"
}

module "backend" {
  source        = "./modules/server"
  name          = "backend"
  instance_type = "t3.medium"
}

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.