地形aws_dynamodb_table_item -将多行JSON插入属性

s4n0splo  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(84)

我有以下terraform配置:

resource "aws_dynamodb_table_item" "my_table" {
  table_name = aws_dynamodb_table.my_table.name
  hash_key   = aws_dynamodb_table.my_table.hash_key

  item = <<ITEM
{
  "id": {"S": "nameAndCodes"},
  "data": {"S": "[
    {
      "code": "03",
      "displayName": "name1"
    },
    {
      "code": "04",
      "displayName": "name2"
    }
  ]"}
}
ITEM
}

当计划阶段执行时,我收到错误:

Error: Invalid format of "item": Decoding failed: invalid character '\r' in string literal

我能让它工作的唯一方法是把整个json变成一行,如下所示:

"data": {"S": "[{\"code\": \"03\", \"displayName\": \"name1\"},{\"code\": \"04\", \"displayName\": \"name2\"}]"

这看起来很难看,很难管理。
有人知道如何在〈〈ITEM块中输入多行JSON吗?

gywdnpxw

gywdnpxw1#

要解决这个问题,您可以使用jsonencode函数来设置项值,并将整个JSON对象放入其中。下面是我的项目中Terraform的一个示例,它创建了一个DynamoDB表并放置了一个初始项。

resource "aws_dynamodb_table" "customer_table" {
name           = "customer"
billing_mode   = "PAY_PER_REQUEST"
hash_key       = "customerId"
stream_enabled = false
attribute {
  name = "customerId"
  type = "S"
 }
}

resource "aws_dynamodb_table_item" "customer_table_item" {
  table_name = aws_dynamodb_table.customer_table.name
  hash_key   = aws_dynamodb_table.customer_table.hash_key
  depends_on = [aws_dynamodb_table.customer_table]
  item = jsonencode({
  "customerId" : {
    "S" : "1"
 },
  "firstName" : {
    "S" : "John"
  },
  "lastName" : {
    "S" : "Doe"
  },
})
}

命令:terrform initterraform fmtterraform planterraform apply

相关问题