Как запустить AWS Lambda из API Gateway несколькими способами? - PullRequest
0 голосов
/ 01 апреля 2019

Я использую облачную информацию для определения шлюза API, для которого определены 4 метода: GET, POST, PUT и DELETE.

Я хочу использовать эти 4 метода для запуска моей лямбды. Когда этот шаблон развернут. Лямбда показывает только с помощью метода DELETE шлюза API.

Как я могу определить свою лямбду в облачной информации, чтобы она использовала все 4 метода?

Resources:
lambdaExecutionRole:
Type: "AWS::IAM::Role"
Properties:
  Path: /
  AssumeRolePolicyDocument:
    Version: 2012-10-17
    Statement:
      - Effect: Allow
        Principal:
          Service:
            - lambda.amazonaws.com
        Action:
          - sts:AssumeRole
  ManagedPolicyArns:
    - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"

lambdaFunction:
Type: AWS::Lambda::Function
Properties:
  FunctionName: !Ref AWS::StackName
  VpcConfig:
    SubnetIds:
      - {"Fn::ImportValue": !Sub "${networkStackName}-${AWS::Region}-privateSubnetAZ1"}
      - {"Fn::ImportValue": !Sub "${networkStackName}-${AWS::Region}-privateSubnetAZ2"}
    SecurityGroupIds:
      - {"Fn::ImportValue": !Sub "${securityStackName}-${AWS::Region}-sgDNSRestrictedAccess"}
  Runtime: dotnetcore2.1
  Handler: MY::LAMBDA.HANDLER::NAME
  MemorySize: 128
  Role: !GetAtt lambdaExecutionRole.Arn
  Timeout: 30
  Code:
    S3Bucket: bucket-name
    S3Key: bucket-key.zip

lambdaInvokePermission:
Type: "AWS::Lambda::Permission"
Properties:
  FunctionName: !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}"
  Action: 'lambda:InvokeFunction'
  Principal: apigateway.amazonaws.com
  SourceArn: !Sub "arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGatewayRestApi}/*"
DependsOn:
  - lambdaFunction

apiGatewayRestApi:
Type: "AWS::ApiGateway::RestApi"
Properties:
  Name: !Ref AWS::StackName
  EndpointConfiguration:
    Types:
      - REGIONAL

apiGatewayResourcePath:
Type: "AWS::ApiGateway::Resource"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ParentId: !GetAtt 
    - apiGatewayRestApi
    - RootResourceId
  PathPart: !Ref apiGatewayProxyPath
DependsOn:
  - apiGatewayRestApi

apiGatewayPostMethod:
Type: "AWS::ApiGateway::Method"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ResourceId: !Ref apiGatewayResourcePath
  HttpMethod: POST
  AuthorizationType: NONE
  Integration:
    Type: AWS_PROXY
    IntegrationHttpMethod: POST
    Uri: !Join
      - ":"
      - - "arn"
        - !Ref AWS::Partition
        - "apigateway"
        - !Ref AWS::Region
        - "lambda:path/2015-03-31/functions/arn"
        - !Ref AWS::Partition
        - "lambda"
        - !Ref AWS::Region
        - !Ref AWS::AccountId
        - "function"
        - !Join
          - "/"
          - - !Sub "${AWS::StackName}"
            - "invocations"
DependsOn:
  - apiGatewayResourcePath

apiGatewayGetMethod:
Type: "AWS::ApiGateway::Method"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ResourceId: !Ref apiGatewayResourcePath
  HttpMethod: GET
  AuthorizationType: NONE
  Integration:
    Type: AWS_PROXY
    IntegrationHttpMethod: GET
    Uri: !Join
      - ":"
      - - "arn"
        - !Ref AWS::Partition
        - "apigateway"
        - !Ref AWS::Region
        - "lambda:path/2015-03-31/functions/arn"
        - !Ref AWS::Partition
        - "lambda"
        - !Ref AWS::Region
        - !Ref AWS::AccountId
        - "function"
        - !Join
          - "/"
          - - !Sub "${AWS::StackName}"
            - "invocations"
DependsOn:
  - apiGatewayResourcePath

apiGatewayPutMethod:
Type: "AWS::ApiGateway::Method"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ResourceId: !Ref apiGatewayResourcePath
  HttpMethod: PUT
  AuthorizationType: NONE
  Integration:
    Type: AWS_PROXY
    IntegrationHttpMethod: PUT
    Uri: !Join
      - ":"
      - - "arn"
        - !Ref AWS::Partition
        - "apigateway"
        - !Ref AWS::Region
        - "lambda:path/2015-03-31/functions/arn"
        - !Ref AWS::Partition
        - "lambda"
        - !Ref AWS::Region
        - !Ref AWS::AccountId
        - "function"
        - !Join
          - "/"
          - - !Sub "${AWS::StackName}"
            - "invocations"
DependsOn:
  - apiGatewayResourcePath

apiGatewayDeleteMethod:
Type: "AWS::ApiGateway::Method"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ResourceId: !Ref apiGatewayResourcePath
  HttpMethod: DELETE
  AuthorizationType: NONE
  Integration:
    Type: AWS_PROXY
    IntegrationHttpMethod: DELETE
    Uri: !Join
      - ":"
      - - "arn"
        - !Ref AWS::Partition
        - "apigateway"
        - !Ref AWS::Region
        - "lambda:path/2015-03-31/functions/arn"
        - !Ref AWS::Partition
        - "lambda"
        - !Ref AWS::Region
        - !Ref AWS::AccountId
        - "function"
        - !Join
          - "/"
          - - !Sub "${AWS::StackName}"
            - "invocations"
DependsOn:
  - apiGatewayResourcePath

apiGatewayDeployment:
Type: "AWS::ApiGateway::Deployment"
Properties:
  RestApiId: !Ref apiGatewayRestApi
DependsOn:
  - apiGatewayPostMethod
  - apiGatewayGetMethod
  - apiGatewayDeleteMethod
  - apiGatewayPutMethod

apiGatewayStage:
Type: "AWS::ApiGateway::Stage"
Properties:
  StageName: app
  RestApiId: !Ref apiGatewayRestApi
  DeploymentId: !Ref apiGatewayDeployment
  MethodSettings:
    - ResourcePath: !Sub "/${apiGatewayProxyPath}"
      HttpMethod: POST
      MetricsEnabled: true
      LoggingLevel: INFO
    - ResourcePath: !Sub "/${apiGatewayProxyPath}"
      HttpMethod: GET
      MetricsEnabled: true
      LoggingLevel: INFO
    - ResourcePath: !Sub "/${apiGatewayProxyPath}"
      HttpMethod: PUT
      MetricsEnabled: true
      LoggingLevel: INFO
    - ResourcePath: !Sub "/${apiGatewayProxyPath}"
      HttpMethod: DELETE
      MetricsEnabled: true
      LoggingLevel: INFO
DependsOn:
  - apiGatewayDeployment

1 Ответ

0 голосов
/ 01 апреля 2019

IntegrationHttpMethod всегда POST для Lambda proxy интеграции.См. Интеграция с лямбда-прокси - шаг 5

Важно

Для лямбда-интеграций необходимо использовать HTTP-метод POST для запроса на интеграцию в соответствии со спецификациейдействия службы Lambda для вызовов функций.Роль IAM в apigAwsProxyRole должна иметь политики, позволяющие службе apigateway вызывать функции Lambda.Дополнительные сведения о разрешениях IAM см. В разделе Модель разрешений шлюза API для вызова API.

Таким образом, например, интеграция вашего метода GET должна выглядеть следующим образом:

apiGatewayGetMethod:
Type: "AWS::ApiGateway::Method"
Properties:
  RestApiId: !Ref apiGatewayRestApi
  ResourceId: !Ref apiGatewayResourcePath
  HttpMethod: GET
  AuthorizationType: NONE
  Integration:
    Type: AWS_PROXY
    IntegrationHttpMethod: POST
    Uri: !Join
      - ":"
      - - "arn"
        - !Ref AWS::Partition
        - "apigateway"
        - !Ref AWS::Region
        - "lambda:path/2015-03-31/functions/arn"
        - !Ref AWS::Partition
        - "lambda"
        - !Ref AWS::Region
        - !Ref AWS::AccountId
        - "function"
        - !Join
          - "/"
          - - !Sub "${AWS::StackName}"
            - "invocations"
DependsOn:
  - apiGatewayResourcePath
...