簡體   English   中英

如何在 terraform 中運行 forloop inside 字符串模板?

[英]How do I run a forloop inside string template in terraform?

我的資源如下所示,如何為下面的用例運行 forloop,我手動放置aws_account_ids變量的每個索引。

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
}

我嘗試遵循此https://discuss.hashicorp.com/t/dynamic-policy-generation-error-policy-contains-an-invalid-json-invalid-character-after-array-element/38881/5但出現錯誤

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

通常的方法是將所有內容包裝在jsonencode中並使用正則 TF 表達式,而不是 json 字符串:

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"
      ]
    }]
    }
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM