Matt W
Matt W

Reputation: 12424

Changing hash_key with Terraform causes Table already exists error

I have a DynamoDB table created with this Terraform:

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"
  }
}

The table was successfully populated (with 4 records, as noted in this post) but in order to solve the problem (in that post) I have added a field PK and set that as the hash_key field, with this:

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"
  }
}

This has caused the following error, when running terraform apply:

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

What do I need to do in the .tf to get the change accepted?

Upvotes: 3

Views: 4278

Answers (1)

Balu Vyamajala
Balu Vyamajala

Reputation: 10373

Changing some of the attributes in DynamoDB is not permitted, for example, changing Partition key, adding a Local Secondary Index, etc.

When such changes occur, it will need to replace the resource and to replace, it will try to delete and re-create the resource. During this process, if table already exists, it will fail.

Only option is to delete the stack or manually delete the DynamoDB Table and let template create it again. Or Renaming the table.

Documentation says it will force new resource

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

Upvotes: 3

Related Questions