terraform to conditionally create ECR repository if not exists

Viewed 1483

I am using terraform to deploy my resources. I have a terraform code to create a ECR repository here:

resource "aws_ecr_repository" "main" {
  name                 = var.repo_name
  image_tag_mutability = var.image_tag_mutability
  image_scanning_configuration {
    scan_on_push = true
  }
}

The above code works fine. However, if the ECR repository already exists in AWS, it throws the error.

For the solution, I wanted to use the terraform data statement to query if the repository exists:

data "aws_ecr_repository" "repository" {
name = var.repo_name
}

resource "aws_ecr_repository" "main" {
  name                 = data.aws_ecr_repository.repository.name
  image_tag_mutability = var.image_tag_mutability
  image_scanning_configuration {
    scan_on_push = true
  }
}

It's throwing error like this:

Error: ECR Repository (digital-service) not found

Any suggestions are appreciated.

0 Answers
Related