CloudFormation - 为 DynamoDB 创建启用 TTL Table

CloudFormation - Enable TTL for DynamoDB Create Table

我想通过 CloudFormation 为我新创建的 table 启用 TTL。我尝试了以下无济于事:

{
  "Resources" : {
    "mytable" : {
      "Type" : "AWS::DynamoDB::Table",
      "Properties" : {
        "TableName" : "my_table",
        "ProvisionedThroughput" : {"ReadCapacityUnits" : 1, "WriteCapacityUnits" : 5},
        "KeySchema" :
        [
          {"AttributeName" : "user_email", "KeyType" : "HASH"},
          {"AttributeName" : "datetime", "KeyType" : "RANGE"}
        ],
        "AttributeDefinitions": [
          {"AttributeName" : "user_email", "AttributeType" : "S"},
          {"AttributeName" : "datetime", "AttributeType" : "S"}
        ],
        "TimeToLiveDescription": {
          "AttributeName": "expire_at", 
          "TimeToLiveStatus": "ENABLED"
        }
      }
    }
}

我使用了从 this doc 获得的 TimeToLiveDescription。

尝试创建堆栈时出现以下错误:

Encountered unsupported property TimeToLiveDescription

link 是 AWS CLI 的示例。

对配置 DynamoDB TTL 的支持尚未添加到 cloudformation。

AWS Dynamo DB 的 TTL 是一项新功能(于 2017 年 2 月推出),就像 Jared 在他的回答中提到的那样,AWS Cloudformation 似乎还不支持它。同时,如果您在同一个 cloudformation 模板中启动一个新的 EC2 实例,您可以做的是执行(在 UserData 下)您链接到的 aws cli 命令,将更新 TTL aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl",引用您的发电机数据库资源(mytable)。 (还要确保实例正在使用具有必要策略的 IAM 角色,以便能够更新此资源)。

现在存在对 CloudFormation 的 DynamoDB TTL 支持。参见:

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-timetolivespecification.html

示例:

{
  "TableName": "MyTable",
  "AttributeDefinitions": [
    {
      "AttributeName": "Uid",
      "AttributeType": "S"
    }
  ],
  "KeySchema": [
    {
      "AttributeName": "Uid",
      "KeyType": "HASH"
    }
  ],
  "ProvisionedThroughput": {
    "ReadCapacityUnits": "1",
    "WriteCapacityUnits": "1"
  },
  "TimeToLiveSpecification": {
    "AttributeName": "TimeToLive",
    "Enabled": "TRUE"
  }
}

为了完整起见,以下是一个 CloudFromation YAML 示例,它创建了一个 Table 并启用了 TTL

AWSTemplateFormatVersion: '2010-09-09'
Description: The database for my Service

Resources:
  BatchDataTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: "MyDynamoTable"
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: Id
          AttributeType: S
        - AttributeName: SortKey
          AttributeType: S
      KeySchema: 
        - AttributeName: Id
          KeyType: "HASH"
        - AttributeName: SortKey
          KeyType: "RANGE"           
      TimeToLiveSpecification:
        AttributeName: TimeToLive
        Enabled: true

现在,如果您使用名为 "TimeToLive" 的属性将项目添加到此表,并将其值设置为项目应过期的 Unix 纪元,DynamoDB 将从 table 当达到 TTL 时。