amazon-web-servicesterraformterraform-provider-awsamazon-ecr

Terraform attempts to recreate ECR repositories after code refactoring


I have the following piece of code in TFE v.1.13. It works as intended but feels a bit repetitive:

resource "aws_ecr_repository" "repository-a" {
  name                 = "repo-a"
  #skipped 
}
    
resource "aws_ecr_repository" "repository-b" {
  name                 = "repo-b"
  #skipped
}
    
resource "aws_ecr_repository" "repository-c" {
  name                 = "repo-c"
  #skipped
}

So, I have refactored it as follows:

locals {
  repo_table = [
    {
      repo_id = "repo-id-a"
      repo_name = "repo-a"
    },
    {
      repo_id = "repo-id-b"
      repo_name = "repo-b"
    },
    {
      repo_id = "repo-id-c" 
      repo_name = "repo-c"
    }
  ]
}

resource "aws_ecr_repository" "repositories" {
  for_each = {for repo in local.repo_table : repo.repo_id => repo }
    
  name                 = each.value.repo_name
  #skipped
}

I got the following pair of errors on apply for each of the three:

Error: ECR Repository (repo-a) not empty, consider using force_delete: RepositoryNotEmptyException: The repository with name 'repo-a' in registry with id '123456789' cannot be deleted because it still contains images

Error: creating ECR Repository (repo-a): RepositoryAlreadyExistsException: The repository with name 'repo-a' already exists in the registry with id '123456789'

So, Terraform tries to delete and recreate each of them, but it can't do that because there are images in there. Is there any way to refactor the code but avoid deleting existing images/repos ?


Solution

  • Since the repositories already exist in the state terraform keeps, you cannot just remove the old blocks and recreate the repositories with the same names, as they are already known to terraform. You could try using a combination of locals (which you already have) and import block. Based on your question, the import would look something like the following:

    locals {
      repo_table = [
        {
          repo_id = "repo-id-a"
          repo_name = "repo-a"
        },
        {
          repo_id = "repo-id-b"
          repo_name = "repo-b"
        },
        {
          repo_id = "repo-id-c" 
          repo_name = "repo-c"
        }
      ]
    }
    
    import {
      for_each = local.repo_table
      to       = aws_ecr_repository.repositories[each.key]
      id       = each.value.repo_name
    }
    
    resource "aws_ecr_repository" "repositories" {
      for_each = local.repo_table
      name     = each.value.repo_name
    }
    

    After you do this, you should be able to remove the import block entirely, and nothing would change.