Get a list of created resources in terraform

1k views Asked by At

I am creating AWS ECR repositories via terraform

resource "aws_ecr_repository" "repo1" {
  name                 = "repo1"
  image_tag_mutability = "MUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }
}
resource "aws_ecr_repository" "repo2" {
  name                 = "repo2"
  image_tag_mutability = "MUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }
}

Now I want to attach a policy to all ECR repositories.

Question is, is there a dynamic way to create a list of all the resources (of type ECR) created using the terraform script? If yes then we can have a for_each on that list and attach a policy.

Or is there any better way to do it?

P.S. I know I can attach policy by writing the following for each. I want to avoid duplication and avoid a case where policy is not attached if the block is missed by someone

resource "aws_ecr_lifecycle_policy" "insights_repository_policy" {
  repository = aws_ecr_repository.insights_repository.name

  policy = local.ecr_cleanup_policy
}

Edit: Question 2 There are some accounts I want to give access to. If I use list of repositories to create and then I want to assign policies for each account then it would make nested for loops. Is there a cleaner solution for that?

local {
  accounts = {test=account_id_123, prod=account_id_456}
}
resource "aws_ecr_repository_policy" "access-permission" {
  for_each   = local.accounts
  policy = <<POLICY
...
POLICY
  repository = aws_ecr_repository.repo_template.name

}
1

There are 1 answers

3
Marcin On BEST ANSWER

Not in your form. It would be better if you used for_each or count. For example:

variable "repos" {
  default = ["repo1", "repo2"]
}


resource "aws_ecr_repository" "repo" {
  for_each             = to_set(var.repos)
  name                 = each.key
  image_tag_mutability = "MUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }
}

then you can do:

resource "aws_ecr_lifecycle_policy" "insights_repository_policy" {
  for_each   = aws_ecr_repository.repo
  repository = each.value.name
  policy = local.ecr_cleanup_policy
}