AWS API Gateway REST API 是否没有设置来禁用 CloudFormation 模板中的 execute-api 端点?

Is there no setting for AWS API Gateway REST API to disable execute-api endpoint in CloudFormation template?

我已经使用 CloudFormation 模板设置了 API 网关(v1,而非 v2)REST API 资源。最近我注意到还创建了默认的 execute-api 端点,我可以在设置中将其禁用。

这个API的类型是AWS::ApiGateway::RestApi

当然,我希望通过模板来完成,所以问题是:是否可以在 CloudFormation 模板中定义此设置,而不是必须在 AWS 控制台中手动单击?此选项可用于 APIGateway V2 API 资源(AWS::ApiGatewayV2::Api),但不适用于 APIGateway V1 REST API 资源 (AWS::ApiGateway::RestApi) 在 CloudFormation 模板中,即使它可以在控制台中为 APIGateway V1 REST API 手动更改。

AWS::ApiGateway::RestApi还有一个CLI way of doing this

以下是我用来搜索此设置的一些链接:
AWS::ApiGatewayV2::API
AWS::ApiGateway::RestApi
Disabling default api-execute endpoint via CLI

您可以通过简单的 custom resource 禁用它。下面是一个 完全有效的 模板的示例:


Resources:

  MyRestApi:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Description: A test API
      Name: MyRestAPI


  LambdaBasicExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action: sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  MyCustomResource:
    Type: Custom::DisableDefaultApiEndpoint
    Properties:
      ServiceToken: !GetAtt 'MyCustomFunction.Arn'
      APIId: !Ref 'MyRestApi'

  MyCustomFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.lambda_handler
      Description: "Disable default API endpoint"
      Timeout: 30
      Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
      Runtime: python3.7
      Code:
        ZipFile: |
          import json
          import logging
          import cfnresponse
          import boto3
          
          logger = logging.getLogger()
          logger.setLevel(logging.INFO)

          client = boto3.client('apigateway')

          def lambda_handler(event, context):
            logger.info('got event {}'.format(event))  
            try:

              responseData = {}

              if event['RequestType'] in ["Create"]:                      
                
                APIId = event['ResourceProperties']['APIId']                
                
                response = client.update_rest_api(
                    restApiId=APIId,
                    patchOperations=[
                        {
                            'op': 'replace',
                            'path': '/disableExecuteApiEndpoint',
                            'value': 'True'
                        }
                    ]
                )

                logger.info(str(response))

                cfnresponse.send(event, context, 
                                 cfnresponse.SUCCESS, responseData)

              else:
                logger.info('Unexpected RequestType!') 
                cfnresponse.send(event, context, 
                                  cfnresponse.SUCCESS, responseData)

            except Exception as err:

              logger.error(err)
              responseData = {"Data": str(err)}
              cfnresponse.send(event,context, 
                               cfnresponse.FAILED,responseData)
            return              

如果有人偶然发现这个使用 CDK 的答案,可以使用 AwsCustomResource 构造简洁地完成(无需定义 Lambda 函数):

const restApi = new apigw.RestApi(...);
const executeApiResource = new cr.AwsCustomResource(this, "execute-api-resource", {
  functionName: "disable-execute-api-endpoint",
  onCreate: {
    service: "APIGateway",
    action: "updateRestApi",
    parameters: {
      restApiId: restApi.restApiId,
      patchOperations: [{
        op: "replace",
        path: "/disableExecuteApiEndpoint",
        value: "True"
      }]
    },
    physicalResourceId: cr.PhysicalResourceId.of("execute-api-resource")
  },
  policy: cr.AwsCustomResourcePolicy.fromStatements([new iam.PolicyStatement({
    effect: iam.Effect.ALLOW,
    actions: ["apigateway:PATCH"],
    resources: ["arn:aws:apigateway:*::/*"],
  })])
});
executeApiResource.node.addDependency(restApi);

禁用默认执行的支持-api端点最近已添加到AWS::ApiGateway::RestApi cloudformation:DisableExecuteApiEndpoint

MyRestApi:
  Type: 'AWS::ApiGateway::RestApi'
  Properties:
    DisableExecuteApiEndpoint: true

您可以在 AWS CDK 中禁用它。这是通过找到 CloudFormation 资源并将其设置为 true 来完成的。

   const api = new apigateway.RestApi(this, 'api', );
   (api.node.children[0] as apigateway.CfnRestApi).addPropertyOverride('DisableExecuteApiEndpoint','true')