Home > Software design >  How do I run a forloop inside string template in terraform?
How do I run a forloop inside string template in terraform?

Time:11-24

My resource looks like below, how to run a forloop for below usecase where I am putting each index of aws_account_ids variable manually.

resource "aws_ecr_repository_policy" "ecr_image_pull_access" {
  repository = aws_ecr_repository.ecr_repo.name
  policy     = <<EOF
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::${var.aws_account_ids[0]}:root",
          "arn:aws:iam::${var.aws_account_ids[1]}:root",
          "arn:aws:iam::${var.aws_account_ids[2]}:root"
        ]
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:GetDownloadUrlForLayer"
      ]
    }
  ]
}
EOF
}

I tried following this https://discuss.hashicorp.com/t/dynamic-policy-generation-error-policy-contains-an-invalid-json-invalid-character-after-array-element/38881/5 but getting error

| var.aws_account_ids is list of string with 3 element
│ 
│ Cannot include the given value in a string template: string required.

CodePudding user response:

The usual way is to wrap everything in jsonencode and use regular TF expressions, instead of json string:

resource "aws_ecr_repository_policy" "ecr_image_pull_access" {
  repository = aws_ecr_repository.ecr_repo.name
  policy     = jsonencode({
    Version = "2008-10-17"
    Statement = [{
      Sid = "AllowPull",
      Effect = "Allow"
      Principal = {
        AWS = [for acc_id in var.aws_account_ids: "arn:aws:iam::${acc_id}:root"]
      },
      Action = [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:GetDownloadUrlForLayer"
      ]
    }]
    }
  )
}
  • Related