繁体   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