terraform模块中的可选映射变量

Jon*_*red 5 amazon-dynamodb terraform

不确定这是否可行,但我有一个DynamoDb表模块,我想让global_secondary_index属性可选,但我无法弄清楚如何做到这一点.

我有以下模块

resource "aws_dynamodb_table" "basic_dynamodb_table" {
  name                = "${var.table_name}"
  read_capacity       = "${var.read_capacity}"
  write_capacity      = "${var.write_capacity}"
  hash_key            = "${var.primary_key}"

  attribute {
    name            = "${var.primary_key}"
    type            = "${var.primary_key_type}"
  }

  global_secondary_index = ["${var.global_secondary_index}"]
}

variable "table_name" {}

variable "read_capacity" {
  default     = "1"
}

variable "write_capacity" {
  default     = "1"
}

variable "primary_key" {}

variable "primary_key_type" {}

variable "global_secondary_index" {
  default = {}
  type = "map"
  description = "This should be optional"
}
Run Code Online (Sandbox Code Playgroud)

它会被使用

module "test-table" {
  source              = "./modules/DynamoDb"

  table_name          = "test-table"
  primary_key         = "Id"
  primary_key_type    = "S"

  global_secondary_index = {
    name = "by-secondary-id"
    hash_key = "secondaryId"
    range_key = "type"
    projection_type = "INCLUDE"
    non_key_attributes = [
        "id"
    ]
    write_capacity = 1
    read_capacity = 1
  }
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

  • 不使用[]插值并得到global_secondary_index: should be a list错误
  • 只是使用var global_secondary_index = ["${var.global_secondary_index}"]get global_secondary_index.0: expected object, got string错误
  • 有条件但显然不支持列表或地图
  • 合并地图global_secondary_index = ["${merge(var.global_secondary_index,map())}"]也会global_secondary_index.0: expected object, got string出错

关于如何使这项工作现在的想法

Pau*_*aul 2

似乎缺少一个功能:

https://github.com/hashicorp/terraform/issues/3388

该主题的变体(将地图列表传递到资源中):

https://github.com/hashicorp/terraform/issues/12294 https://github.com/hashicorp/terraform/issues/7705

最后要注意的一件事是,在条件条件上你可以偷偷地使用它们。

resource "some_tf_resource" "meh" {
  count = "${length(keys(var.my_map)) > 0 ? 1 : 0}"
  # other resource settings here
}
Run Code Online (Sandbox Code Playgroud)

使用 count 并将其设置为 0 是解决早期版本中缺乏条件的 terraforms 的黑客方法。它仍然有效=)

不过,如果还有其他资源依赖于该meh资源,情况很快就会变得丑陋,所以如果可以避免的话,我不会经常使用它。