首页 > 解决方案 > 使用 AWS sam 创建具有自定义域的 Rest API 时出现 KeyError

问题描述

使用这个 Makefile :

.PHONY: build

build:
    sam build

# API_URL: https://api.crystallize.com/[MY TENANT]/search
# DOMAIN_NAME: subdomain.domain.com (domain.com is registered in route53)
# ZONE_ID : Id of the HostedZone created by Route53 Registrar (21 characters)
# CERT_ARN : Arn of a certificate (arn:aws:acm:us-east-1:XXXXX:certificate/YYYYY)
deploy:
    sam deploy --debug --parameter-overrides \
    ApiUrl=${API_URL} \ 
    TokenId=${TOKEN_ID} \
    TokenSecret=${TOKEN_SECRET} \
    DomainName=${DOMAIN_NAME} \
    ZoneId=${ZONE_ID} \
    CertArn=${CERT_ARN}

这个模板:(灵感来自:https ://github.com/aws-samples/sessions-with-aws-sam/blob/master/custom-domains/rest/template.yaml )

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: grange-api

Parameters:
  DomainName:
    Type: String
    Description: Domian name for api
  ZoneId:
    Type: String
    Description: Zone ID if exists. If not leave as none.
    Default: none
  CertArn:
    Type: String
    Description: Certificate ARN if exists. If not leave as none.
    Default: none
  TokenId:
    Type: String
    Description: Crystallize Token Id.
  TokenSecret:
    Type: String
    Description: Crystallize Token Secret.
  ApiUrl:
    Type: String
    Description: Crystallize Api Url.

Conditions:
  CreateZone:
    !Equals [!Ref ZoneId, 'none']
  CreateCert:
    !Equals [!Ref CertArn, 'none']

Resources:

  GeneratedZone: # If a Zone ID is not passed in the parameteres, then a new zone is created for the domain
    Type: AWS::Route53::HostedZone
    Condition: CreateZone
    Properties: 
      Name: !Ref DomainName

  GeneratedCert: # If a Certificate ARN is not passed in the parameters, then a new cert is created and will required validation during the deploy
    Type: AWS::CertificateManager::Certificate
    Condition: CreateCert
    Properties: 
      DomainName: !Ref DomainName
      ValidationMethod: DNS

  RestApiGateway: # Creates a REST API endpoint under the custom domain
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Domain:
        DomainName: !Ref DomainName
        CertificateArn: !If [CreateCert, !Ref GeneratedCert, !Ref CertArn]
        Route53:
          HostedZoneId: !If [CreateZone, !Ref GeneratedZone, !Ref ZoneId]
    
  CreateOrderFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: create-order/
      Handler: create-order
      Runtime: go1.x
      Tracing: Active 
      Events:
        CatchAll:
          Type: Api 
          Properties:
            Path: /order
            Method: POST
            RestApiId: !Ref RestApiGateway

      Environment: 
        Variables:
          TOKEN_ID: !Ref TokenId
          TOKEN_SECRET: !Ref TokenSecret
          API_URL: !Ref ApiUrl


当我运行“make && make deploy”时,我有一个永远持续的“等待创建变更集”而不是像这样的错误:

2021-04-21 07:41:55,888 | Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
2021-04-21 07:41:55,889 | Using config file: samconfig.toml, config environment: default
2021-04-21 07:41:55,889 | Expand command line arguments to:
2021-04-21 07:41:55,889 | --template_file=/home/thalion/projects/grange/api/grange-api/.aws-sam/build/template.yaml --parameter_overrides={'ApiUrl': 'https://api.crystallize.com/[mytenant]/search', 'TokenId': '[MY TOKEN ID]', 'TokenSecret': '[MY TOKEN SECRET]', 'DomainName': '[MY DOMAIN NAME]', 'ZoneId': '[MY ZONE ID]', 'CertArn': '[MY CERT ARN]'} --stack_name=lacantoch-api --s3_bucket=[MY S3 BUCKET] --s3_prefix=lacantoch-api --fail_on_empty_changeset --confirm_changeset --capabilities=['CAPABILITY_IAM'] 
2021-04-21 07:41:56,650 | File with same data is already exists at lacantoch-api/715faa37049a733cbe4b82aaf82e997f. Skipping upload

        Deploying with following values
        ===============================
        Stack name                   : lacantoch-api
        Region                       : eu-west-3
        Confirm changeset            : True
        Deployment s3 bucket         : [MY S3 BUCKET]
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {"ApiUrl": "https://api.crystallize.com/[mytenant]/search", "TokenId": "[MY TOKEN ID]", "TokenSecret": "[MY TOKEN SECRET]", "DomainName": "[MY DOMAIN NAME]", "ZoneId": "[MY ZONE ID]", "CertArn": "[MY CERT ARN]"}
        Signing Profiles             : {}

Initiating deployment
=====================
2021-04-21 07:41:56,689 | Collected default values for parameters: {'ZoneId': 'none', 'CertArn': 'none'}
2021-04-21 07:41:56,715 | 4 stacks found in the template
2021-04-21 07:41:56,715 | Collected default values for parameters: {'ZoneId': 'none', 'CertArn': 'none'}
2021-04-21 07:41:56,737 | 4 resources found in the stack 
2021-04-21 07:41:56,737 | Collected default values for parameters: {'ZoneId': 'none', 'CertArn': 'none'}
Uploading to lacantoch-api/022d64fc3d20c3a435b0ec915a86d687.template  2449 / 2449  (100.00%)

Waiting for changeset to be created..
2021-04-21 07:52:00,223 | Sending Telemetry: {'metrics': [{'commandRun': {'requestId': '[AN ID]', 'installationId': '[AN ID]', 'sessionId': '[AN ID]', 'executionEnvironment': 'CLI', 'ci': False, 'pyversion': '3.7.10', 'samcliVersion': '1.22.0', 'awsProfileProvided': False, 'debugFlagProvided': True, 'region': 'eu-west-3', 'commandName': 'sam deploy', 'duration': 604334, 'exitReason': 'KeyError', 'exitCode': 255}}]}
2021-04-21 07:52:00,884 | HTTPSConnectionPool(host='aws-serverless-tools-telemetry.us-west-2.amazonaws.com', port=443): Read timed out. (read timeout=0.1)
Traceback (most recent call last):
  File "samcli/lib/deploy/deployer.py", line 290, in wait_for_changeset
  File "botocore/waiter.py", line 53, in wait
  File "botocore/waiter.py", line 358, in wait
botocore.exceptions.WaiterError: Waiter ChangeSetCreateComplete failed: Max attempts exceeded

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "samcli/__main__.py", line 12, in <module>
  File "click/core.py", line 829, in __call__
  File "click/core.py", line 782, in main
  File "click/core.py", line 1259, in invoke
  File "click/core.py", line 1066, in invoke
  File "click/core.py", line 610, in invoke
  File "samcli/lib/cli_validation/image_repository_validation.py", line 76, in wrapped
  File "click/decorators.py", line 73, in new_func
  File "click/core.py", line 610, in invoke
  File "samcli/lib/telemetry/metric.py", line 153, in wrapped
  File "samcli/lib/telemetry/metric.py", line 122, in wrapped
  File "samcli/lib/utils/version_checker.py", line 42, in wrapped
  File "samcli/cli/main.py", line 90, in wrapper
  File "samcli/commands/deploy/command.py", line 230, in cli
  File "samcli/commands/deploy/command.py", line 343, in do_cli
  File "samcli/commands/deploy/deploy_context.py", line 162, in run
  File "samcli/commands/deploy/deploy_context.py", line 230, in deploy
  File "samcli/lib/deploy/deployer.py", line 456, in create_and_wait_for_changeset
  File "samcli/lib/deploy/deployer.py", line 295, in wait_for_changeset
KeyError: 'StatusReason'
[5665] Failed to execute script __main__
make: *** [Makefile:7: deploy] Error 255

当我尝试使用这个单独创建函数的模板时,它可以工作:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: grange-api

Parameters:
  TokenId:
    Type: String
    Description: Crystallize Token Id.
  TokenSecret:
    Type: String
    Description: Crystallize Token Secret.
  ApiUrl:
    Type: String
    Description: Crystallize Api Url.

Resources:    
  CreateOrderFunction:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: create-order/
      Handler: create-order
      Runtime: go1.x
      Tracing: Active 
      Events:
        CatchAll:
          Type: Api 
          Properties:
            Path: /order
            Method: POST

      Environment: 
        Variables:
          TOKEN_ID: !Ref TokenId
          TOKEN_SECRET: !Ref TokenSecret
          API_URL: !Ref ApiUrl

但我无法使用自定义域名创建 API!帮助 !

标签: amazon-web-servicesaws-api-gatewayaws-serverlessaws-sam

解决方案


推荐阅读