terraform conditionally create ecr repository if not exist

I’m using the below code in order to create ECR repo, yet, I fail to change it “conditionally create” …

resource "aws_ecr_repository" "ecr_repository" {
  for_each = local.repositories
  name     = each.key


  image_scanning_configuration {
      scan_on_push = true
  }

  tags = var.tags
}

resource "aws_ecr_lifecycle_policy" "default_policy" {
  for_each   = local.repositories
  repository = aws_ecr_repository.ecr_repository[each.key].name

  policy = jsonencode({rules = concat(local.untagged_images_rule, local.pull_request_images_rule, local.remove_max_images_rule)})

  depends_on = [
    aws_ecr_repository.ecr_repository
  ]
}

Adding count = data.external.check_repo.result.success == "true" ? 0 : 1 fails as well … Is there a way to have “loop” resource which “call” the “aws_ecr_repository” ? Any other way ?

I think you want to create a repository if and only if the repository does not already exist.

You could use aws_ecr_repositories data source to get a list of existing repositories:

data "aws_ecr_repositories" "repositories" {}

and then build some logic that only includes a repository in local.repositories if it doesn’t exist in data.aws_ecr_repositories.repositories.names.

Hope that helps.

@jamiekt, trying to do that when the resource does not exist can cause terraform to alternately create then destroy the resource in many cases. Some situations may allow you to filter the data source such that the new resource would not show up in the next run, but that’s not universally true.

This is similar to the request to conditionally import a resource, but there is currently no way to handle either type of configuration in a general way.

1 Like

@jbardin thx for the response, good to know.