1

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?

Colin Dean
  • 1,429
  • 1
  • 15
  • 26

1 Answers1

8

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}
Brandon Miller
  • 4,695
  • 1
  • 20
  • 27
  • Your snippet is virtually the same as mine, in which Terraform was managing it. I did `terraform destroy` at some point and it destroyed the ECR repos. – Colin Dean Jun 06 '18 at 18:35
  • 5
    If you are using the `data` source and not the `resource` its not managed. Verify you dont have a `resource "aws_ecr_repository"` defined anywhere. Your second code block indicates you are referencing a resource and not a data source even though your first code block says its a data source. Check for the other one in your code. – Brandon Miller Jun 06 '18 at 20:17
  • I must have had it as a resource at some point. It seems to be working fine now. – Colin Dean Jun 15 '18 at 16:10
  • One note for anyone reading these: If you previously had a "resource" and you switched it to "data" and did terraform apply it will delete the resource the first time you run terraform apply (because it's a change to the config). After that the "data" will be respected and it will not be created or deleted. – josh803316 Nov 22 '21 at 19:15
  • @josh803316 you can remove it from the state file and it wont destroy anything. Just use the [state removal command](https://www.terraform.io/docs/cli/commands/state/rm.html) – Brandon Miller Nov 23 '21 at 20:08
  • Thanks Brandon! – josh803316 Nov 24 '21 at 21:13