首页 > 解决方案 > 无法将列表值分配给 Terraform 中的 json 策略

问题描述

我在 Terraform 中有这个政策:

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "execute-api:Invoke",
        "Resource": "*",
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": "${source_ip}"
            }
        }
      }
    ]
  }

我有一个这样定义的变量 authorized_ip :

variable "authorized_ip" {
  default = [
    "x.x.x.x/x",
    "x.x.x.x/x",
  ]
}

现在我以这种方式调用 Json 策略:

data "template_file" "apigw_policy" {
  template = "${file("${path.module}/template/apigateway_policy.json.template")}"

   vars = {
      source_ip = "${var.authorized_ip}"
   }
}

但我收到了这个错误:

属性“vars”的值不合适:元素“source_ip”:需要字符串。

所以 Terraform 需要一个字符串而不是列表。如何将列表转换为 String 以获得这样的结果:

"IpAddress": {
   "aws:SourceIp": [
      "x.x.x.x/x",
      "x.x.x.x/x"
    ]
 }

标签: amazon-web-servicesterraform

解决方案


您可以在此处使用该jsonencode功能

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "${jsonencode(source_ip)}"
                }
            }
        }
    ]
}

推荐阅读