How can I declare and reference an ECR repository in Terraform without jeopardizing its contents?

5.5k Views Asked by At

I am building a Terraform configuration to deploy some containers to AWS ECS. Obviously, I must push the Docker images to ECR. I created a repository in ECR and pushed the images.

Now I'm automating. If I declare the aws_ecr_repository like so:

data "aws_ecr_repository" "service" {
  name = "myrepository"
}

then Terraform will manage it. I can eventually reference it with something like

image = "${aws_ecr_repository.myrepository.repository_url}"

in the process of building the ECS task definition.

I am under the impression that Terraform will delete this repository – or fail when it has images – when I run terraform destroy as a part of my development cycle. This would be bad, because then terraform destroy would either never complete or I would have to clear out the ECR repository for that command to complete successfully.

How can I best reference an ECR repository that already exists but I seemingly don't want Terraform to manage because Terraform may destroy data that lives outside of Terraform, i.e. the Docker images uploaded by release CI jobs?

1

There are 1 best solutions below

6
On

If you don't want Terraform to manage it use the data source. This lets you get the data like this:

data "aws_ecr_repository" "example" {
  name = "example"
}

Then reference the url like:

${data.aws_ecr_repository.example.repository_url}