通过 terraform 添加多个 DynamoDB 集合项

Adding multiple DynamoDB set items through terraform

地形版本:0.12.20

我想在 terraform 中添加多个具有 set 数据类型的项目,我浏览了 link,其中一个示例展示了如何将简单数据类型添加为 String,但它无法使用 Set[=18= 添加]

下面是我正在测试的代码

resource "aws_dynamodb_table_item" "items" {
  hash_key   = "key"
  table_name = "test"
  for_each = {
    "72" = {
      test = ["114717","2"],
      test1 = []
    },
    "25" = {
      test = ["114717"],
      test1 = []
    }
  }
  item = <<EOF
{
  "key": {"S": "${each.key}"},
  "test": {"SS": "${each.value.test}"},
  "test1": {"SS": "${each.value.test1}"}
}
EOF
}

但是,它失败了 Cannot include the given value in a string template: string required.

我试过

resource "aws_dynamodb_table_item" "items" {
  hash_key   = "key"
  table_name = "test"
  for_each = {
    "72" = {
      test = "114717,2",
      test1 = ""
    },
    "25" = {
      test = "114717",
      test1 = ""
    }
  }
  item = <<EOF
{
  "key": {"S": "${each.key}"},
  "test": {"SS": ["${each.value.test}"]},
  "test1": {"SS": ["${each.value.test1}"]}
}
EOF
}

这无法将 "114717,2" 区分为两个不同的项目

在第二个例子中,我什至也尝试了下面的部分

{
  "key": {"S": "${each.key}"},
  "test": {"SS": "${split(",",each.value.test)}"},
  "test1": {"SS": "${split(",",each.value.test1)}"}
}

这也失败了 Cannot include the given value in a string template: string required.

我希望能够将值拆分为数组 ["114717","2"]。这将帮助我将值存储为 DynamoDB

中的 Set

您的 item 应该 有效 json。为此,您可以使用 jsonencode:

resource "aws_dynamodb_table_item" "items" {
  hash_key   = "key"
  table_name = "GameScores"
  for_each = {
    "72" = {
      test = ["114717","2"],
      test1 = []
    },
    "25" = {
      test = ["114717"],
      test1 = []
    }
  }
  item = <<EOF
{
  "key": {"S": "${each.key}"},
  "test": {"SS": ${jsonencode(each.value.test)}},
  "test1": {"SS": ${length(each.value.test1) > 0 ? jsonencode(each.value.test1) : jsonencode([""])}}
}
EOF
}

另外 SS 不能为空,所以你必须考虑到这一点。因此,您必须检查并使用 [""] 数组。或者你必须重新考虑如果你的 test1[].

该怎么办