使用 AWS CloudFormation 为私有 API 创建自定义域名 - Amazon API Gateway

使用 AWS CloudFormation 为私有 API 创建自定义域名

以下示例 AWS CloudFormation 模板创建私有 API 和私有自定义域名,将私有 API 映射到自定义域名,然后创建域名访问关联。您需要提供自己的 VPC 端点、域名和证书 ARN。

以下注意事项可能会影响您使用 AWS CloudFormation 创建私有自定义域名。

  • 您不能使用 AWS CloudFormation 拒绝域名访问关联。要拒绝域名访问关联,请使用 AWS CLI。

  • 使用 AWS::ApiGateway::DomainNameV2 AWS CloudFormation 属性创建私有自定义域名。

  • 使用 AWS::ApiGateway:BasePathMappingV2 AWS CloudFormation 属性创建基本路径映射。

AWSTemplateFormatVersion: 2010-09-09 Parameters: EndpointID: Type: String Default: vpce-abcd1234567efg Description: A VPC endpoint with enableDnsHostnames and enableDnsSupport set to true. DomainName: Type: String Default: private.example.com Description: A domain name that you own. CertificateArn: Type: String Default: arn:aws:acm:us-west-2:123456789:certificate/abcd-000-1234-0000-000000abcd Description: An ACM certificate that covers the domain name. Resources: PrivateApi: Type: 'AWS::ApiGateway::RestApi' Properties: EndpointConfiguration: Types: - PRIVATE VpcEndpointIds: - !Ref EndpointID Name: private-api Policy: Statement: - Action: 'execute-api:Invoke' Effect: Allow Principal: '*' Resource: 'execute-api:/*' - Action: 'execute-api:Invoke' Condition: StringNotEquals: 'aws:SourceVpce': !Ref EndpointID Effect: Deny Principal: '*' Resource: 'execute-api:/*' Version: 2012-10-17 PrivateApiDeployment: Type: 'AWS::ApiGateway::Deployment' Properties: RestApiId: !Ref PrivateApi Description: Private API deployment DependsOn: - PrivateApiMethod PrivateApiStage: Type: 'AWS::ApiGateway::Stage' Properties: RestApiId: !Ref PrivateApi DeploymentId: !Ref PrivateApiDeployment StageName: prod PrivateApiMethod: Type: 'AWS::ApiGateway::Method' Properties: HttpMethod: ANY ResourceId: !GetAtt PrivateApi.RootResourceId RestApiId: !Ref PrivateApi AuthorizationType: NONE Integration: Type: MOCK RequestTemplates: application/json: "{\"statusCode\": 200}" IntegrationResponses: - StatusCode: '200' MethodResponses: - StatusCode: '200' PrivateDomainName: Type: AWS::ApiGateway::DomainNameV2 Properties: DomainName: !Ref DomainName CertificateArn: !Ref CertificateArn EndpointConfiguration: Types: - PRIVATE SecurityPolicy: TLS_1_2 Policy: Statement: - Action: 'execute-api:Invoke' Effect: Allow Principal: '*' Resource: 'execute-api:/*' - Action: 'execute-api:Invoke' Condition: StringNotEquals: 'aws:SourceVpce': !Ref EndpointID Effect: Deny Principal: '*' Resource: 'execute-api:/*' Version: 2012-10-17 PrivateBasePathMapping: Type: AWS::ApiGateway::BasePathMappingV2 DependsOn: - PrivateApiStage Properties: BasePath: prod DomainNameArn: !GetAtt PrivateDomainName.DomainNameArn RestApiId: !Ref PrivateApi Stage: prod DomainNameAccessAssociation: Type: AWS::ApiGateway::DomainNameAccessAssociation Properties: DomainNameArn: !GetAtt PrivateDomainName.DomainNameArn AccessAssociationSource: !Ref EndpointID AccessAssociationSourceType: VPCE