Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a list of created resources in terraform

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading