我有一个用例,我需要创建3个dynamodb表,但只有命名约定更改了
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"
}
}
我需要用两个不同的名称创建同一个表,如MN_SKU_COLOR和CH_SKU_COLOR目前,我正在复制资源并赋予一个新名称
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"
}
}
在不复制代码的情况下创建资源3次的最佳方法是什么?
如果唯一的区别是名称,那么您可以执行:
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"
}
}
然后使用variable中的名称引用各个表,例如
aws_dynamodb_table.table["MN_SKU_COLOR"].id
将for_each
与名称集或列表一起使用:https://www.terraform.io/language/meta-arguments/for_each