TerraformPilot

DevOps

Fix Terraform Error - Error Creating ECR Repository - RepositoryAlreadyExistsException

Fix RepositoryAlreadyExistsException when creating ECR repositories in Terraform. Import existing repos, configure lifecycle policies, and manage image cleanup.

LLuca Berton1 min read

Quick Answer

#

An ECR repository with that name already exists in your AWS account and region. Import it with terraform import aws_ecr_repository.app my-app, or use a unique name.

The Error

#
Error: error creating ECR Repository: RepositoryAlreadyExistsException: 
The repository with name 'my-app' already exists in the registry 
with id '123456789012'

What Causes This

#
  • Repository created outside Terraform (Console, CLI, CI/CD pipeline)
  • Previous Terraform apply succeeded but state was lost
  • Multiple configs managing the same repository name

How to Fix It

#

Solution 1: Import the Existing Repository

#
terraform import aws_ecr_repository.app my-app

Solution 2: Full Repository Configuration

#
resource "aws_ecr_repository" "app" {
  name                 = "${var.project}/${var.environment}/app"
  image_tag_mutability = "IMMUTABLE"  # Prevent tag overwrites
 
  image_scanning_configuration {
    scan_on_push = true
  }
 
  encryption_configuration {
    encryption_type = "AES256"
  }
}
 
# Clean up old images automatically
resource "aws_ecr_lifecycle_policy" "app" {
  repository = aws_ecr_repository.app.name
 
  policy = jsonencode({
    rules = [{
      rulePriority = 1
      description  = "Keep last 10 images"
      selection = {
        tagStatus   = "any"
        countType   = "imageCountMoreThan"
        countNumber = 10
      }
      action = { type = "expire" }
    }]
  })
}

Solution 3: Delete and Recreate

#
# WARNING: This deletes all images in the repository
aws ecr delete-repository --repository-name my-app --force
terraform apply

Troubleshooting Checklist

#
  1. ✅ Does the repository exist? (aws ecr describe-repositories --repository-names my-app)
  2. ✅ Can you import it?
  3. ✅ Is the name unique in this account + region?
  4. ✅ Do you need the existing images? (Don't force-delete if yes)
#

Conclusion

#

ECR repository names are unique per account per region. Import existing repositories with terraform import, add lifecycle policies to manage image cleanup, and use namespaced names (project/env/app) to organize repositories.

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

Share this article