Vijaya Senthil Kumar
Vijaya Senthil Kumar

Reputation: 41

Adding multiple DynamoDB items through terraform

How to add multiple items in dynamoDB table?

  table_name = "${var.environment}-kaleidos-dynamodb-MappingConfig"
  hash_key   = "eventType"
  item = <<EOF
   json
EOF
}````

DynamoDB always expects one item. Is there a way to provide multiple items?

Upvotes: 3

Views: 8202

Answers (2)

Sarath
Sarath

Reputation: 2844

If someone is looking to insert set datatype here is an example

resource "aws_dynamodb_table_item" "employee" {
  table_name = "${var.environment}-employee"
  hash_key   = "id"
  for_each = {
    "1234abcd" = {
      fistName             = "Jack"
      lastName             = "Dorsey"
      projects             =  ["Twiter", "Square"]
    }
    "34589fsd" = {
      fistName             = "Jack"
      lastName             = "MA"
      projects             =  ["Alibaba", "Ant"]
    }
  }
  item = <<ITEM
{
  "id": {"S": "${each.key}"},
  "fistName": {"S": "${each.value.fistName}"},
  "lastName": {"S": "${each.value.lastName}"},
  "projects": {"SS": ${jsonencode(each.value.projects)}}
}
ITEM
}

Upvotes: 0

sleepy_keita
sleepy_keita

Reputation: 1508

There's no way to add multiple items using a single resource "aws_dynamodb_table_item". You can have multiple resource statements in the same file, as long as you give them different names, for example:

resource "aws_dynamodb_table_item" "item1" {
  ...
}

resource "aws_dynamodb_table_item" "item2" {
  ...
}

If you are trying to create items based on an array or map or a specific number, you can use count or for_each (for_each was introduced in 0.12.6)

count example:

resource "aws_dynamodb_table_item" "items" {
  count = 4
  item <<EOF
{
  "pk": {"S": "${count.index}"}
}
EOF

for_each example:

resource "aws_dynamodb_table_item" "items" {
  for_each = {
    item1 = {
      something = "hello"
    }
    item2 = {
      something = "hello2"
    }
  }
  item = <<EOF
{
  "pk": {"S": "${each.key}"},
  "something": {"S": "${each.value.something}"}
}
EOF
}

Upvotes: 8

Related Questions