Terraform:从地图上获取值的问题

时间:2020-02-05 06:53:51

标签: terraform terraform-provider-aws

我正在尝试从地图中获取值,并给出以下错误。

错误:

Error: Incorrect attribute value type

  on ../../modules/lb-rules/rules.tf line 71, in resource "aws_alb_listener_rule" "http_header":
  71:         http_header_name = keys(lookup(var.listener_rules, "http_header_name", null))
    |----------------
    | var.listener_rules is object with 3 attributes

Inappropriate value for attribute "http_header_name": string required.

main.tf

module example {
...
...
listener_rules = {
    ...
    "http_header_name" = {
      "x-header" = "sample_server"
    }
  } 
    ...
}

rules.tf

resource "aws_alb_listener_rule" http_header {
  listener_arn = var.public_alb_listener_arn
  priority     = var.priority_number

  action {
    type             = "forward"
    target_group_arn = aws_alb_target_group.default.id
  }

  dynamic "condition" {
    for_each = lookup(var.listener_rules, "http_header_name", null)
    content {
      http_header {
        http_header_name = keys(lookup(var.listener_rules, "http_header_name", null))
        values           = ["hi"]
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否在这里完全理解了您的目标,但看起来这个想法是要在此condition属性中为每个元素生成一个http_header_name块。对于Terraform v0.12.20或更高版本,这是一种编写方法:

resource "aws_alb_listener_rule" http_header {
  listener_arn = var.public_alb_listener_arn
  priority     = var.priority_number

  action {
    type             = "forward"
    target_group_arn = aws_alb_target_group.default.id
  }

  dynamic "condition" {
    for_each = try(var.listener_rules.http_header_name, {})
    content {
      http_header {
        http_header_name = condition.key
        values           = [condition.value]
      }
    }
  }
}