【问题标题】:Can't assign list value to json policy in Terraform无法将列表值分配给 Terraform 中的 json 策略
【发布时间】:2019-06-24 21:57:56
【问题描述】:

我在 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 需要一个字符串而不是列表。 如何将列表转换为字符串以获得这样的结果:

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

【问题讨论】:

标签: amazon-web-services terraform


【解决方案1】:

您可以在此处使用jsonencode function

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

【讨论】:

    【解决方案2】:

    试试

    "aws:SourceIp": ["${join(", ", source_ip)}"]
    

    请注意,"[" and "]" 不在用于在策略内定义列表的插值值之外,但不代表 Terraoform list 类型。

    编辑:修正了下面评论中提到的错字。

    【讨论】:

    • 谢谢它的工作,这只是一个小错字 "aws:SourceIp": ["${join(", ", source_ip)}"]
    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 2018-07-17
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多