The Error
When running terraform plan or terraform apply, you may encounter:
Error: Duplicate resourceThis error is common and usually straightforward to fix once you understand the cause.
Common Causes
1. Configuration Issues
The most frequent cause is a misconfiguration in your .tf files:
- Incorrect resource references or attribute names
- Missing required arguments
- Type mismatches in expressions
2. State Issues
Terraform state can get out of sync:
# Check current state
terraform state list
# Show specific resource
terraform state show <resource_address>
# Refresh state from real infrastructure
terraform refresh3. Provider or Version Issues
Provider updates can introduce breaking changes:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
required_version = ">= 1.5.0"
}Step-by-Step Fix
Step 1: Get Detailed Output
# Run plan with verbose logging
TF_LOG=DEBUG terraform plan 2>&1 | tee plan-debug.log
# Validate configuration
terraform validateStep 2: Check Your Configuration
# Format and validate
terraform fmt -recursive
terraform validate
# Check for unused declarations
terraform plan -detailed-exitcodeStep 3: Apply the Fix
Based on your diagnosis, update your configuration:
# Example: Fix resource dependencies
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
depends_on = [aws_security_group.web]
}Step 4: Verify
# Plan again to confirm fix
terraform plan
# Apply with auto-approve (only in CI/CD)
terraform applyPrevention
- Use terraform validate before every plan
- Pin provider versions in required_providers
- Use terraform fmt for consistent formatting
- Implement CI/CD with plan review before apply
- Enable state locking to prevent concurrent modifications
- Use modules for reusable, tested configurations
Related Resources
Master Terraform and Infrastructure as Code with Luca Bertonβs courses β practical, hands-on training for DevOps engineers.
