首页 > 解决方案 > 为什么 AWS SAM 给我随机的 DynamoDB 表名

问题描述

当我使用 SAM 创建我的 Lambda、API 网关和 DynamoDB 表时,它都可以正常工作,直到我到达实际创建的表。它应该被称为“列表”,但是在“列表”这个词之后它给了我一堆随机数字和字母。我想要做的是,当所有 3 个服务都创建后,它们应该相互通信,但是由于我遇到了这个问题,我必须手动将名称添加到我的函数中才能正常工作。

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Resources:
  ClickSam:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.8
      CodeUri: Lambda/
      MemorySize: 128
      Timeout: 3
      Environment:
        Variables:
          TABLE_NAME: !Ref List
          REGION_NAME: !Ref AWS::Region
      Events:
        ClickAPI:
          Type: Api
          Properties:
            Path: /visits
            Method: GET
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref List

List:
  Type: AWS::Serverless::SimpleTable
  Properties:
    PrimaryKey:
      Name: url
      Type: String

---------- 这是我为表创建项目的 Lambda 函数代码。

import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.client('dynamodb')
response = dynamodb.update_item(
TableName='List', 
Key={
    'url':{'S': "etc.com"}
},
UpdateExpression='ADD visits :inc',
ExpressionAttributeValues={
    ':inc': {'N': '1'}
},
ReturnValues="UPDATED_NEW"
)

response = {
'statusCode': 200,
'headers': {
    "Content-Type" : "application/json",
    "Access-Control-Allow-Origin" : "*",
    "Allow" : "GET, OPTIONS, POST",
    "Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
    "Access-Control-Allow-Headers" : "*"
},
'body': json.dumps(int(response["Attributes"]["visits"]["N"]))
}
return response

标签: python-3.xamazon-dynamodbserverless-application-model

解决方案


使用TableName参数来修复表名(参见AWS::Serverless::SimpleTable)。

Type: AWS::Serverless::SimpleTable
Properties:
  TableName: MyTable

AWS::DynamoDB::Table资源的文档:

如果您不指定名称,AWS CloudFormation 会生成一个唯一的物理 ID 并将该 ID 用作表名称。


推荐阅读