I have a used case where,
I need to create 3 dynamodb tables but only the naming convention changes
resource "aws_dynamodb_table" "GB_SKU_COLOR" {
name = "GB_SKU_COLOR_${var.stage}"
billing_mode = "PAY_PER_REQUEST"
hash_key = "PRODUCT_ID"
stream_enabled = true
stream_view_type = "NEW_AND_OLD_IMAGES"
attribute {
name = "PRODUCT_ID"
type = "S"
}
}
I need to create the same table with 2 different names, like MN_SKU_COLOR and CH_SKU_COLOR
Currently, am replicating the resource and giving a new name
resource "aws_dynamodb_table" "MN_SKU_COLOR" {
name = "MN_SKU_COLOR_${var.stage}"
billing_mode = "PAY_PER_REQUEST"
hash_key = "PRODUCT_ID"
stream_enabled = true
stream_view_type = "NEW_AND_OLD_IMAGES"
attribute {
name = "PRODUCT_ID"
type = "S"
}
}
resource "aws_dynamodb_table" "CH_SKU_COLOR" {
name = "CH_SKU_COLOR_${var.stage}"
billing_mode = "PAY_PER_REQUEST"
hash_key = "PRODUCT_ID"
stream_enabled = true
stream_view_type = "NEW_AND_OLD_IMAGES"
attribute {
name = "PRODUCT_ID"
type = "S"
}
}
What is the best way to create the resource 3 times without replicating the code ?
2
Answers
Use
for_each
along with a set or list of names: https://www.terraform.io/language/meta-arguments/for_eachIf the only difference is in name, then you can do:
Then you refer to the individual tables using their name from variabile, e.g.