地形规划 'string required' dynamodb_table_item

terraform plan 'string required' dynamodb_table_item

我需要将一组字符串添加到 dynamodb_table_item 资源。

# my.tfvars

client_days = [
  "2021-05-08",               # May
  "2021-06-12", "2021-06-26", # June
]

# main.tf
variable "client_days" {
  type        = set(string)
  description = "Client days."
}

resource "aws_dynamodb_table_item" "client_days" {
  table_name = aws_dynamodb_table.periods.name
  hash_key   = "name"

  item = <<EOF
{
  "name": { "S": "client-days" },
  "days": {
      "SS" : "${client_days}"
  }
}
EOF
}

结果如下所示:

 32:   item = <<EOF
  33: {
  34:   "name": { "S": "client-days" },
  35:   "days": {
  36:       "SS" : "${var.client_days}"
  37:   }
  38: }
  39: EOF
    |----------------
    | var.client_days is set of string with 11 elements

Cannot include the given value in a string template: string required.

我不知道如何解决这个问题。 我还尝试使用 join().

将该列表转换为字符串

你必须使用 jsonencode:

resource "aws_dynamodb_table_item" "client_days" {
  table_name = "testdb"
  hash_key   = "name"

  item = <<EOF
{
  "name": { "S": "client-days" },
  "days": {
      "SS" : ${jsonencode(var.client_days)}
  }
}
EOF
}

对于完全期望 JSON 的参数,通常最好使用 jsonencode 生成整个值,这样可以避免各种 JSON 语法和 Terraform 模板问题:

resource "aws_dynamodb_table_item" "client_days" {
  table_name = "testdb"
  hash_key   = "name"

  item = jsonencode({
    name = {
      S = "client-days"
    }
    days = {
      SS = var.client_days
    }
  })
}

这样您就可以在 jsonencode 的参数中混合使用静态数据和引用,而无需任何字符串模板。