You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过AWS CloudFormation创建RDS并恢复现有备份的方案咨询

解决方案:通过CloudFormation创建RDS实例并从现有数据库备份恢复

方案一:手动创建快照 + CloudFormation恢复(快速实现)

1. 生成现有RDS的手动快照

  • 控制台操作:进入RDS控制台,选中目标数据库,点击「操作」→「拍摄快照」,设置快照名称(例如existing-db-snapshot-20240520),等待快照状态变为可用。
  • CLI命令:
    aws rds create-db-snapshot \
      --db-instance-identifier 你的现有RDS实例ID \
      --db-snapshot-identifier existing-db-snapshot-20240520
    
    验证快照状态:
    aws rds describe-db-snapshots --db-snapshot-identifier existing-db-snapshot-20240520
    
    等待Status字段变为available。

2. 编写CloudFormation模板恢复新实例

模板示例(按需调整配置):

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  RestoredDBInstance:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t3.micro # 替换为所需实例类型
      DBSnapshotIdentifier: existing-db-snapshot-20240520 # 替换为你的快照ID
      Engine: mysql # 必须与源数据库引擎一致(如postgres/sqlserver)
      VPCSecurityGroups:
        - sg-1234567890abcdef0 # 替换为你的安全组ID
      StorageType: gp3
      MultiAZ: false # 按需开启多AZ

3. 部署CloudFormation栈

  • 控制台:上传模板,填写栈名称后启动创建。
  • CLI命令:
    aws cloudformation create-stack \
      --stack-name restored-rds-stack \
      --template-body file://rds-restore-template.yaml
    
    等待栈创建完成,新实例将自动从快照恢复数据。

方案二:全自动化(CloudFormation + Lambda自定义资源)

如果需要自动触发快照创建并完成恢复,可通过Lambda自定义资源实现端到端自动化:

1. 创建Lambda函数(处理快照创建逻辑)

Python代码示例:

import boto3
import time
import json
import urllib3

rds = boto3.client('rds')

def lambda_handler(event, context):
    db_instance_id = event['ResourceProperties']['DBInstanceIdentifier']
    snapshot_id = event['ResourceProperties']['DBSnapshotIdentifier']
    
    if event['RequestType'] == 'Create':
        # 触发快照创建
        rds.create_db_snapshot(
            DBInstanceIdentifier=db_instance_id,
            DBSnapshotIdentifier=snapshot_id
        )
        # 等待快照可用
        while True:
            snapshot = rds.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id)['DBSnapshots'][0]
            if snapshot['Status'] == 'available':
                break
            time.sleep(30)
        # 返回快照ID给CloudFormation
        send_response(event, context, 'SUCCESS', {'DBSnapshotIdentifier': snapshot_id})
    elif event['RequestType'] == 'Delete':
        # 可选:删除快照(按需保留)
        try:
            rds.delete_db_snapshot(DBSnapshotIdentifier=snapshot_id)
        except Exception as e:
            print(f"删除快照失败: {e}")
        send_response(event, context, 'SUCCESS', {})

def send_response(event, context, response_status, response_data):
    response_body = json.dumps({
        'Status': response_status,
        'Reason': f"查看CloudWatch日志流: {context.log_stream_name}",
        'PhysicalResourceId': context.log_stream_name,
        'StackId': event['StackId'],
        'RequestId': event['RequestId'],
        'LogicalResourceId': event['LogicalResourceId'],
        'Data': response_data
    })
    http = urllib3.PoolManager()
    http.request('PUT', event['ResponseURL'], body=response_body, headers={'Content-Type': ''})

给Lambda函数添加IAM权限:允许rds:CreateDBSnapshot、rds:DescribeDBSnapshots、rds:DeleteDBSnapshot及CloudWatch日志权限。

2. 编写CloudFormation自动化模板

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  SnapshotLambda:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.12
      Handler: index.lambda_handler
      Code:
        ZipFile: |
          # 粘贴上面的Lambda代码
      Role: !GetAtt LambdaRole.Arn

  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: {Service: lambda.amazonaws.com}
            Action: sts:AssumeRole
      Policies:
        - PolicyName: RDSSnapshotAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: [rds:CreateDBSnapshot, rds:DescribeDBSnapshots, rds:DeleteDBSnapshot]
                Resource: '*'
              - Effect: Allow
                Action: [logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents]
                Resource: '*'

  AutoCreateSnapshot:
    Type: Custom::CreateDBSnapshot
    Properties:
      ServiceToken: !GetAtt SnapshotLambda.Arn
      DBInstanceIdentifier: 你的现有RDS实例ID
      DBSnapshotIdentifier: auto-snapshot-20240520 # 自定义快照名称

  RestoredDB:
    Type: AWS::RDS::DBInstance
    Properties:
      DBInstanceClass: db.t3.micro
      DBSnapshotIdentifier: !GetAtt AutoCreateSnapshot.DBSnapshotIdentifier
      Engine: mysql
      VPCSecurityGroups: [sg-1234567890abcdef0]
      StorageType: gp3
    DependsOn: AutoCreateSnapshot # 确保快照就绪后再创建实例

3. 部署自动化栈

上传模板启动创建,CloudFormation会自动触发Lambda创建快照,待快照可用后自动恢复新RDS实例。


关键注意事项

  • 引擎一致性:新实例的引擎必须与源数据库完全匹配(如源为MySQL 8.0,新实例引擎需指定mysql)。
  • 资源权限:确保CloudFormation使用的IAM角色具备读取快照、创建RDS实例的权限;跨账户场景需先共享快照。
  • 存储配置:新实例的存储容量不能小于快照的实际大小。
  • 费用优化:若无需保留快照,在Lambda的Delete事件中添加删除逻辑,避免额外存储费用。

内容的提问来源于stack exchange,提问作者MANPREET KAUR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:14:57