使用 Terraform 更改 hash_key 会导致 Table 已存在错误

Changing hash_key with Terraform causes Table already exists error

我有一个使用此 Terraform 创建的 DynamoDB table:

resource "aws_dynamodb_table" "materials_table" {
  name              = "materials"
  hash_key          = "MATERIAL"
  billing_mode      = "PROVISIONED"
  read_capacity     = 5
  write_capacity    = 5
  
  attribute {
    name = "MATERIAL"
    type = "S"
  }
}

table 已成功填充(有 4 条记录,如 中所述)但为了解决问题(在 post 中)我添加了一个字段 PK 并将其设置为 hash_key 字段,其中:

resource "aws_dynamodb_table" "materials_table" {
  name              = "materials"
  hash_key          = "PK"
  billing_mode      = "PROVISIONED"
  read_capacity     = 5
  write_capacity    = 5
  
  attribute {
    name = "PK"
    type = "S"
  }
}

这导致了以下错误,当 运行 terraform apply:

Error: error creating DynamoDB Table: ResourceInUseException: Table already exists: materials

我需要在 .tf 中做什么才能接受更改?

不允许更改 DynamoDB 中的某些属性,例如更改分区键、添加本地二级索引等

发生此类更改时,将需要替换资源并替换,它将尝试删除并重新创建资源。在此过程中,如果table已经存在,则会失败。

唯一的选择是删除堆栈或手动删除 DynamoDB Table 并让模板重新创建它。或者重命名 table.

Documentation 表示会强制使用新资源

hash_key - (Required, Forces new resource) The attribute to use as the hash (partition) key.