LoginSignup
1
2

TerraformでDynamoDBに一気にデータを突っ込みたい時のやつ

Last updated at Posted at 2024-05-02

結論から

TerraformでMapをListにして突っ込む方法があまり検索に引っかからないのもあり、残しておくことにした。

main.tf
resource "aws_dynamodb_table" "example" {
  name         = "ExampleTable"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "PartitionKey"
  range_key    = "SortKey"

  attribute {
    name = "PartitionKey"
    type = "S"
  }

  attribute {
    name = "SortKey"
    type = "S"
  }

  tags = {
    Name = "ExampleTable"
  }
}

locals {
  list = [
    { PartitionKey = { S = "hoge" }, SortKey = { S = "1" }, Content = { S = "サンプルデータ1" } },
    { PartitionKey = { S = "hoge" }, SortKey = { S = "2" }, Content = { S = "サンプルデータ2" } },
    { PartitionKey = { S = "hoge" }, SortKey = { S = "3" }, Content = { S = "サンプルデータ3" } },
  ]
}

resource "aws_dynamodb_table_item" "example" {
  for_each   = { for i in local.list : "${i.PartitionKey.S}#${i.SortKey.S}" => i }
  table_name = aws_dynamodb_table.example.name
  hash_key   = aws_dynamodb_table.example.hash_key
  range_key  = aws_dynamodb_table.example.range_key
  item       = jsonencode(each.value)
}

解説

for_each"${i.PartitionKey.S}#${i.SortKey.S}"を渡してる理由はDynamoDBの使用上PartitionKeySortKeyを合わせてPrimaryのためMapのキーで文字列結合させているためである。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2