Search code examples
amazon-web-servicesterraformamazon-ecr

build resources based on variable count


may I ask if there is a way to build an aws resource using Terraform v0.14.10 base from the count of the defined variables and use the name of the variable as part of the name of the created ECR resource. Its like I want to build ECR repo and it should be 3 of them coz of the variables I used has 3 and use the name as the repo name like as below:

Results of ECR build creation

app1.repo
pogi2.repo
panget3.repo

Terraform Code:

MY.TF

variable RESOURCE_NAME { type = map }

locals {
  RESOURCE_NAME  = "${var.app-name}-repo"
}

resource "aws_ecr_repository" "myrepo" {
  name = local.RESOURCE_NAME
}

VAR.tfvars

app-name = [ "app1", "pogi2", "panget3" ]

Solution

  • You can do that as follows:

    resource "aws_ecr_repository" "myrepo" {
      for_each = toset(var.app-name)
      name = "${each.key}.repo"
    }