1

我有下一个清单:

local {
...
  step_scaling_out_policy_configuration = {
    "adjustment_type"         = "ChangeInCapacity"
    "cooldown"                = 300
    "metric_aggregation_type" = "Maximum"
    "step_adjustment"         = {
      "metric_interval_lower_bound" = 0
      "scaling_adjustment"          = 1
    }
  }
...
}

我可以使用下一个逻辑转换成块:

  step_scaling_policy_configuration {
    adjustment_type          = local.step_scaling_out_policy_configuration.adjustment_type
    cooldown                 = local.step_scaling_out_policy_configuration.cooldown
    metric_aggregation_type  = local.step_scaling_out_policy_configuration.metric_aggregation_type

    step_adjustment {
      metric_interval_lower_bound = local.step_scaling_out_policy_configuration.step_adjustment.metric_interval_lower_bound
      scaling_adjustment          = local.step_scaling_out_policy_configuration.step_adjustment.scaling_adjustment
    }
  }

在地图中使用固定数量的键非常容易。但是是否可以动态生成这样的块,因为我不知道local.step_scaling_out_policy_configuration地图中到底有什么。现在假设我有

local {
...
  step_scaling_out_policy_configuration = {
    "adjustment_type"         = "ChangeInCapacity"
    "cooldown"                = 300
    "metric_aggregation_type" = "Maximum"
    #######
    "some_new_key"            = "value"
    #######
    "step_adjustment"         = {
      "metric_interval_lower_bound" = 0
      "scaling_adjustment"          = 1
    }
  }
...
}

显然,按照以前的逻辑,我不会在块中有some_new_key参数。是否可以根据地图内部的内容动态step_scaling_policy_configuration添加键来阻止?step_scaling_policy_configurationlocal.step_scaling_out_policy_configuration

4

1 回答 1

2

您可以使用try()lookup()来检查密钥是否存在并将其设置为null是否丢失。在大多数提供商null中,就像不设置密钥一样。有时将其设置为显式默认值或空字符串可能是有意义的""null在大多数情况下工作正常并使用提供程序默认值。

示例代码使用try()lookup()解决方案:

step_scaling_policy_configuration {
  ....

  some_new_key   = try(local.step_scaling_out_policy_configuration.some_new_key, null)
  some_other_key = lookup(local.step_scaling_out_policy_configuration, "some_other_key", null)

  step_adjustment {
    ....
  }
}

如果您还想制作step_scaling_policy_configuration和/或step_adjustment依赖本地地图中存在的价值,请查看terraform 文档中的动态块

于 2020-09-08T00:04:07.120 回答