首页 > 解决方案 > DynamoDB 恢复到新表并更新 Terraform

问题描述

我正在为 AWS DynamoDB 使用时间点恢复 (PITR)。

DynamoDB 表A是使用 Terraform 配置的。在表 A 上启用 PITR 后,我设法根据AWS 文档中的说明使用 CLI将其还原到新表A-Backup

还原完成后,我更新了 lambda 以使用新表名A-Backup作为表环境变量的新值。

但现在的问题是如何在 Terraform 中同步此更改以确保 Terraform 反映所做的更改,即从 PITR 创建的新表?

这里的最佳做法是什么?

标签: amazon-web-servicesamazon-dynamodbterraform

解决方案


这是我在还原 DynamoDB 表时用来使 Terraform 保持最新的过程。

示例 Terraform 表

# dynamo.tf
resource "aws_dynamodb_table" "bird_sightings" {
  name = "bird_sightings_original"

  point_in_time_recovery {
    enabled = true
  }
}

使用 AWS CLI 恢复备份

aws dynamodb restore-table-to-point-in-time \
  --source-table-name "bird_sightings_original" \
  --target-table-name "bird_sightings_restored" \
  --restore-date-time `date -v -7d +"%s"` # timestamp for 7 days ago

aws dynamodb wait table-exists --table-name bird_sightings_restored

更新 Terraform 状态并应用缺失的设置

# Remove original table from Terraform state (does not delete table)
terraform state rm aws_dynamodb_table.bird_sightings 

# Update table name in terraform config file
sed -i "s/bird_sightings_original/bird_sightings_restored/g" dynamo.tf

# Import new table into the Terraform state as the original resource
terraform import aws_dynamodb_table.bird_sightings bird_sightings_restored

# Apply settings that AWS does not copy to backups (tags, point in time recovery, stream settings, etc)
terraform apply

Terraform 是对 AWS 恢复过程的一个很好的补充,因为 AWS 不会将所有表设置复制到备份中。Terraform 会告诉您缺少什么并更新您的表格。


推荐阅读