【问题标题】:Why is AWS SAM giving me random DynamoDB table names为什么 AWS SAM 给我随机的 DynamoDB 表名
【发布时间】:2020-11-19 00:15:42
【问题描述】:

当我使用 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.x amazon-dynamodb serverless-application-model


    【解决方案1】:

    使用TableName 参数固定表名(参见AWS::Serverless::SimpleTable)。

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

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

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

    【讨论】:

    • 这解决了我的问题,感谢您的帮助,我从中吸取了教训。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-11-13
    • 2012-05-26
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多