簡體   English   中英

如何使用Cloudformation在AWS API Gateway上設置代理

[英]How set Proxy on AWS API Gateway using Cloudformation

我有一個lambda函數,它將使用Amazon API Gateway {proxy +}處理PUT和GET請求。 通過Amazon Console手動設置所有設置后,它可以正常工作。 但我想使用AWS Cloudformation使其自動化。

為了通知您,我將編寫設置{proxy+}步驟:

1)創建一個簡單的Lambda函數 ,並將以下代碼行粘貼到其中:

import boto3

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": 'text/html',
            "Access-Control-Allow-Origin": "*"
        },
        "body": "Hello Reza Amya, Your Lambda is working..!"
    }

2)轉到Amazon API Gateway ,然后單擊Create API

3)選擇“ New API ,填寫API name ,從“ Endpoint Type ”列表中選擇“ Edge optimized ,然后單擊“ Create API

4)然后創建您的API,並且您應該位於其“ Resources頁面上,否則請轉到“ Resources頁面以獲取所創建的API。

5)從“ Actions選擇“ Create Resource

6)選擇“ Configure as proxy resource (然后它應該自動更改其他字段,如果沒有,請在“ Resource Name鍵入proxy ,在“ Resource Path鍵入{proxy+} ),然后單擊“ Create Resource

7)選擇Lambda Function Proxy for Integration type然后從Lambda Function選擇您的lambda函數,然后單擊Save

8)在“ Add Permission to Lambda Function彈出窗口中,單擊“ Ok

9)從Actions單擊Deploy API

10)從“ Deployment stage的列表中選擇“ New Stage ,然后為“ Stage name鍵入一個Stage name (對我來說,我輸入的是“ api”),然后單擊“ Deploy

11)在已部署API的根頁面上的stage上,您可以看到Invoke URL 單擊它,它將打開新的標簽,該標簽鏈接到這樣的地方: https : //xxxxxxxxx.execute-api.us-east-1.amazonaws.com/api/

12)在您的網址末尾添加一個簡單的段,如下所示: https : //xxxxxxxxx.execute-api.us-east-1.amazonaws.com/api/ test

現在,您應該在瀏覽器頁面中看到以下消息:

Hello Reza Amya, Your Lambda is working..!

現在的問題是我已在Yaml文件中編寫了所有這些步驟:

AWSTemplateFormatVersion: 2010-09-09
Description: My Lambda Function
Parameters:
  S3Bucket:
    Description: S3 Bucket where the Lambda code is
    Type: String
  S3Key:
    Description: S3 Key where the Lambda code is
    Type: String
  S3ObjectVersion:
    Description: Version of the S3 Key to use
    Type: String

Resources:
  apiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "my-api"
      Description: "My API"
      EndpointConfiguration:
        Types:
          - EDGE

  Resource: 
    Type: AWS::ApiGateway::Resource
    Properties: 
      RestApiId: 
        Ref: "apiGateway"
      ParentId: 
        Fn::GetAtt: 
          - "apiGateway"
          - "RootResourceId"
      PathPart: "{proxy+}"

  ProxyMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      HttpMethod: ANY
      ResourceId: !Ref Resource
      RestApiId: !Ref apiGateway
      AuthorizationType: NONE
      RequestParameters:
        method.request.path.proxy: true
      Integration:
        CacheKeyParameters:
          - 'method.request.path.proxy'
        RequestParameters:
          integration.request.path.proxy: 'method.request.path.proxy'
        Type: AWS_PROXY
        IntegrationHttpMethod: ANY
        Uri: !Sub
          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Arn}/invocations
          - Arn:
              Fn::GetAtt:
               - LambdaFunction
               - Arn
        PassthroughBehavior: WHEN_NO_MATCH
        IntegrationResponses:
          - StatusCode: 200 

  apiGatewayDeployment:
    Type: "AWS::ApiGateway::Deployment"
    DependsOn:
      - "ProxyMethod"
    Properties:
      RestApiId: !Ref "apiGateway"
      StageName: "dev"

  IAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: 'sts:AssumeRole'

      Policies:
        - PolicyName: Logging
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: 'arn:aws:logs:*:*:*'
        - PolicyName: AccessToDynamoDB
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'dynamodb:CreateTable'
                  - 'dynamodb:DeleteItem'
                  - 'dynamodb:DeleteTable'
                  - 'dynamodb:GetItem'
                  - 'dynamodb:GetRecords'
                  - 'dynamodb:UpdateItem'
                  - 'dynamodb:UpdateTable'
                  - 'dynamodb:PutItem'
                  - 'dynamodb:UpdateTable'
                Resource: 'arn:aws:dynamodb:*:*:*'

  LambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: {Ref: S3Bucket}
        S3Key: {Ref: S3Key}
        S3ObjectVersion: {Ref: S3ObjectVersion}
      Handler: main.lambda_handler
      MemorySize: 128
      Role: {'Fn::GetAtt': [IAMRole, Arn]}
      Runtime: python3.6
      Timeout: 300

  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt 
        - LambdaFunction
        - Arn
      Action: 'lambda:InvokeFunction'
      Principal: apigateway.amazonaws.com
      SourceArn: !Sub arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/*

Outputs:
  apiGatewayInvokeURL:
    Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGateway}"

  lambdaArn:
    Value: !GetAtt "LambdaFunction.Arn"

上面的Yaml文件將創建Lambda函數並部署API,但是當我嘗試測試API時,它將顯示以下錯誤:

{"message": "Internal server error"}

您能否指導我什么地方出了問題以及如何解決該問題?

該問題與您的IntegrationHttpMethod設置有關。 盡管您的APIGateway方法為ANY ,但對於AWS Lambda, IntegrationHttpMethod必須始終為POST

這將導致以下方法聲明。

  ProxyMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      HttpMethod: ANY
      ResourceId: !Ref Resource
      RestApiId: !Ref apiGateway
      AuthorizationType: NONE
      RequestParameters:
        method.request.path.proxy: true
      Integration:
        CacheKeyParameters:
          - 'method.request.path.proxy'
        RequestParameters:
          integration.request.path.proxy: 'method.request.path.proxy'
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub
          - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Arn}/invocations
          - Arn:
              Fn::GetAtt:
               - LambdaFunction
               - Arn
        PassthroughBehavior: WHEN_NO_MATCH
        IntegrationResponses:
          - StatusCode: 200 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM