I would like to insert to dynamodb table some items which will be defined during using module. During specification parameters in module, user doesn't need to pass all variables because some fields are not required like "timezone".
value of input which is passed to module
locals {
schedules = {
"reyjkavik-time" = {
"timezone" = "Atlantic/Reykjavik"
"description" = "office hours in Reykjavik"
"periods" = ["office-hours"]
}
}
}
locals.tf
schedules = toset(flatten([
for schedule_name, schedule in var.schedules : {
description = schedule.description
timezone = try(schedule.timezone,"")
periods = schedule.periods
}
]))
resource "aws_dynamodb_table_item" "schedules" {
for_each = {
for schedule in local.schedules : schedule.name => schedule
}
table_name = aws_dynamodb_table.config_table.name
hash_key = aws_dynamodb_table.config_table.hash_key
item = jsonencode({
"description" = {
"S" = each.value.description
},
"timezone" = {
"S" = each.value.timezone
},
"periods" = {
"SS" = each.value.periods
},
})
}
but what if user doesn't pass the variable like "timezone"? item will be added to dynamodb with the following format
{
"timezone": {
"S": ""
},
"description": {
"S": "office hours in reyka"
},
"periods": {
"SS": [
"office-hours"
]
}
}
the problem is that I use lambda from AWS lambda https://aws.amazon.com/solutions/implementations/instance-scheduler/ and format of database items are not valid because dynamodb shows that timezone value is empty which is wrong. Ideally if in this case I could insert only two fields (without timezone)
{
"description": {
"S": "office hours in reyka"
},
"periods": {
"SS": [
"office-hours"
]
}
}
CodePudding user response:
You can check for empty string of timezone
and skip it if you want:
resource "aws_dynamodb_table_item" "schedules" {
for_each = {
for schedule in local.schedules : schedule.name => schedule
}
table_name = aws_dynamodb_table.config_table.name
hash_key = aws_dynamodb_table.config_table.hash_key
item = jsonencode(merge({
"description" = {
"S" = each.value.description
}},
each.value.timezone != "" ? {"timezone" = {
"S" = each.value.timezone
}} : null,
{"periods" = {
"SS" = each.value.periods
},
}))
}
Does not look that pretty, but it should do the job.