amazon-web-servicesterraformamazon-dynamodbterraform-provider-awsinfrastructure

using a single Dynamodb resource in terraform and create 3 tables with different names


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 ?


Solution

  • If the only difference is in name, then you can do:

    variable "names" {
      default = ["MN_SKU_COLOR", "GB_SKU_COLOR", "CH_SKU_COLOR"]
    }
    
    
    resource "aws_dynamodb_table" "table" {
       
          for_each     = toset(var.names)  
       
          name         = "${each.key}_${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"
          }
        }
    

    Then you refer to the individual tables using their name from variabile, e.g.

    aws_dynamodb_table.table["MN_SKU_COLOR"].id