当您说您在 Visual Studio 2017 中使用 AWS Toolkit 时,我假设您正在使用 AWS SAM 并构建 CloudFormation 模板(正如您提到的 serverless.template 所推断的那样)。
目前 AWS SAM 不支持使用区域终端节点设置 API 网关。这是GitHub issue目前正在跟踪它
但是,如果您使用的是自定义域,则有一个合理的解决方法。
即使您的 API Gateway 是在 Endpoint 设置为 Edge Optimized 的情况下创建的,您也可以创建一个将 Endpoint 设置为区域的 AWS::ApiGateway::DomainName 资源。
以下是我如何在我的 AWS SAM 模板中实现这一点的示例(我使用 YAML 而不是 JSON,因为它更容易处理多行值)。
注意:AWS::ApiGateway::DomainName 目前不提供有关区域端点的信息,因此我包含了一个自定义资源,它能够检索我们需要的信息。
MyApiGateway:
Type: 'AWS::Serverless::Api'
Properties:
StageName: 'prod'
ApiCertificate:
Type: 'AWS::CertificateManager::Certificate'
Properties:
DomainName: 'api.example.com'
DomainValidationOptions:
- DomainName: 'api.example.com'
ValidationDomain: 'example.com'
CustomResourceLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: 'sts:AssumeRole'
Effect: Allow
Principal:
Service: 'lambda.amazonaws.com'
Path: /
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Policies:
- PolicyName: ApiGateway
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- 'apigateway:*'
Effect: Allow
Resource: '*'
DomainNameInfoCustomResourceFunction:
Type: 'AWS::Lambda::Function'
Properties:
Handler: index.handler
Role: !GetAtt CustomResourceLambdaExecutionRole.Arn
Runtime: 'nodejs6.10'
Timeout: 300
Code:
ZipFile: |
const AWS = require('aws-sdk');
const response = require('cfn-response');
exports.handler = function(event, context) {
const ApiGateway = new AWS.APIGateway();
ApiGateway.getDomainName({
domainName: event.ResourceProperties.DomainName
}, (err, data) => {
if (err != null) {
response.send(event, context, response.FAILED, undefined);
} else {
response.send(event, context, response.SUCCESS, {
DomainName: data.domainName,
RegionalDomainName: data.regionalDomainName,
RegionalHostedZoneId: data.regionalHostedZoneId,
DistributionDomainName: data.distributionDomainName,
DistributionHostedZoneId: data.distributionHostedZoneId
});
}
});
}
ApiDomainName:
Type: 'AWS::ApiGateway::DomainName'
Properties:
DomainName: 'api.example.com'
EndpointConfiguration:
Types:
- REGIONAL
RegionalCertificateArn: !Ref ApiCertificate
ApiBasePathMapping:
Type: 'AWS::ApiGateway::BasePathMapping'
DependsOn: [MyApiGatewayprodStage, ApiDomainName]
Properties:
DomainName: 'api.example.com'
RestApiId: !Ref MyApiGateway
Stage: 'prod'
ApiDomainNameInfo:
Type: 'Custom::DomainNameInfo'
DependsOn: [ApiDomainName, ApiBasePathMapping]
Properties:
ServiceToken: !GetAtt DomainNameInfoCustomResourceFunction.Arn
DomainName: !Ref ApiDomainName
ApiRecordSet:
Type: 'AWS::Route53::RecordSet'
DependsOn: [ApiDomainNameInfo]
Properties:
HostedZoneId: '0123456789' # ENTER YOUR DOMAINS HOSTED ZONE ID
Name: 'api.example.com'
ResourceRecords:
- !GetAtt ApiDomainNameInfo.RegionalDomainName
Type: CNAME
TTL: 60