【问题标题】:Terraform - don't create resource if data source does not existTerraform - 如果数据源不存在,则不要创建资源
【发布时间】:2021-04-05 15:06:45
【问题描述】:

我正在使用以下设置来遍历我的本地人。只有在 terraform 可以抓取数据资源的情况下,才应填写某些参数。如果数据资源不存在,则在参数中注明,然后跳过资源创建。

#Only get the data resource if it exists#################################
data "aws_ssm_parameter" "example_parameter" {
  count        = "${var.does_ssm_parameter_exist == true ? 1 : 0}"
  name         = "ssm_parameter"
}

#List of parameters for all config rules
locals {   
  config_rule_params = {
      "access_keys_rotated" = {
          "input_parameters" = "example"
      },
      "acm_certificate_expiration_check" = {
          #ERROR! Get input parameters from data source if it exists#################################
          "input_parameters" = "${var.does_ssm_parameter_exist == "true" ? "${data.aws_ssm_parameter.example_parameter[count.index].value}" : "DOES_NOT_EXIST"}"
      }
  }

#Only create config rule if input parameters exist
resource "aws_config_config_rule" "parameterised_config_rules" {
  for_each = {
    for rule, params in local.config_rule_params : rule => params
    if params.input_parameters != "DOES_NOT_EXIST"
  }
  input_parameters            = each.value.input_parameters
}

不幸的是,我似乎无法以这种方式使用 count.index:

Error: Reference to "count" in non-counted context
"input_parameters" = "${var.does_ssm_parameter_exist == "true" ? "${data.aws_ssm_parameter.example_parameter[count.index].value}" : "DOES_NOT_EXIST"}"
The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws terraform0.12+ aws-config


    【解决方案1】:

    您在locals 中对count.index 的使用不正确。 count 只能用于资源和模块,不能用于locals。因此,您必须明确指定您想要的参数索引,如下所示:

    "input_parameters" = "${var.does_ssm_parameter_exist == "true" ? "${data.aws_ssm_parameter.example_parameter[0].value}" : "DOES_NOT_EXIST"}"
    

    根据您的 example_parameter 的性质,您可能需要使用常规循环或使用 splat 表达式来获取其所有值。

    【讨论】:

    • 这成功了。似乎任何索引都可以,只要您提到的“计数”参考不包含在本地人中。非常感谢!
    猜你喜欢
    • 2022-11-17
    • 2021-08-01
    • 2017-12-22
    • 2020-04-13
    • 2019-07-26
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2021-01-03
    相关资源
    最近更新 更多