AWS-SAM如何复用已有Route53域名而非重新创建,同时配置basePath?
问题1:解决Route53记录已存在的报错
报错原因是你在HttpApi的Domain配置中指定了Route53字段,SAM会默认尝试为你创建对应域名的A类型记录集,和你已有的记录冲突。你只需要删除Domain下的Route53配置块即可,SAM就不会再尝试创建新的DNS记录,后续手动维护已有Route53记录指向HTTP API的自定义域名端点即可。
问题2:配置basePath
basePath有两种配置场景,按需选择:
- 场景1:给整个API统一添加路径前缀,比如所有接口都挂载到
api.example.com/products/下,在Domain配置中添加BasePath字段即可 - 场景2:仅单个接口使用
/products路径,直接修改Lambda事件的Path属性为/products即可
修改后的完整模板参考:
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > aws-restapi Sample SAM Template for aws-restapi Globals: Function: Timeout: 5 VpcConfig: SecurityGroupIds: - sg-041f24sd125s51e8e SubnetIds: - subnet-05265b2d Parameters: FirebaseProjectId: Type: String DomainName: Type: String Default: api.example.com Resources: AuthGatewayHttpApi: Type: AWS::Serverless::HttpApi Properties: Domain: DomainName: !Ref DomainName CertificateArn: arn:aws:acm:us-east-1:xxxx:certificate/xxxxx-xxxx-xxxx-xxxx-xxxxx # 已删除Route53配置块,避免自动创建DNS记录 BasePath: products # 整个API挂载到/products前缀下,不需要前缀就设为'' Auth: Authorizers: FirebaseAuthorizer: IdentitySource: $request.header.Authorization JwtConfiguration: audience: - !Ref FirebaseProjectId issuer: !Sub https://securetoken.google.com/${FirebaseProjectId} DefaultAuthorizer: FirebaseAuthorizer AuthFunction: Type: AWS::Serverless::Function Properties: CodeUri: aws-restapi/ Handler: source/testfile.lambdaHandler Runtime: nodejs14.x Events: Gateway: Type: HttpApi Properties: ApiId: !Ref AuthGatewayHttpApi Path: /hello # 如果要该接口直接匹配/products,可改为/ Method: get
补充注意事项
- 模板部署完成后,到API Gateway控制台查看自定义域名的
API网关域名值,把你已有的Route53 A记录的目标值修改为这个端点即可完成解析绑定 - 如果你的自定义域名已经在API Gateway中创建过,不需要在HttpApi里重复定义Domain配置,直接创建
AWS::ApiGatewayV2::ApiMapping资源将你的HTTP API挂载到已有自定义域名的对应路径即可
内容的提问来源于stack exchange,提问作者PeakGen
相关产品推荐
相关产品推荐

