天天看點

AWS API Gateway和Lambda的簡單測試具體流程建立Lambda應用建立API GatewayS3 Bucket網頁測試觸發API Gateway和Lambda函數碰到S3 Bucket删除問題術語Reference

文章目錄

  • 具體流程
  • 建立Lambda應用
  • 建立API Gateway
  • S3 Bucket網頁測試觸發API Gateway和Lambda函數
  • 碰到S3 Bucket删除問題
  • 術語
  • Reference

測試了一下使用API Gateway來觸發Lambda應用,并将結果顯示在網頁上。

Lambda支援語言為: Node.js,Java,Python,C#,Go,PowerShell,等等。它具有無需管理伺服器,根據需求自動擴充,便宜等優勢。

具體流程

在S3 Bucket裡存放網頁,顯示網頁後,在網頁裡通過API Gateway來觸發Lambda功能應用,并将Lambda功能應用傳回的結果顯示在網頁上。Route53來使用DNS網址為可選。

建立Lambda應用

Lambda是EC2在一起的Compute界面下,點進去後,再點

Create Function

來建立函數, 取名為:

XiongLambdaFunction

,語言設定為Python 3.6,這樣會自動生成以下代碼:

import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

           

進行以下替換:

import json
def lambda_handler(event, context):
    print("In lambda handler")

    resp = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
        },
        "body": "Xiong Huilin"
    }

    return resp
           

建立API Gateway

建立一個API Gateway,在

Networking & Content Delivery

下點

API Gateway

,選擇

REST

,API取名為:

XiongTestAPI

,在

Actions

下點

Create Method

,選擇

GET

方法,Integration type選擇

Lambda Function

,并選擇前面已經建立的

XiongLambdaFunction

。點儲存,有以下提示。

You are about to give API Gateway permission to invoke your Lambda function:

arn:aws:lambda:ap-southeast-1:606255748358:function:XiongLambdaFunction

Deploy API

對API進行釋出,釋出成功後會有一個URL生成,這個生成的URL将會被用做第三步測試:

Invoke URL: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

S3 Bucket網頁測試觸發API Gateway和Lambda函數

建立兩個檔案:Index.html和error.html,此測試是根據ACloud Guru所做的示例。

在index.html裡,将GET請求的URL替換為: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI,如下html代碼所示:

<html>
<script>

function myFunction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("my-demo").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI", true);
    xhttp.send();

}

</script>
<body><div align="center"><br><br><br><br>
<h1>Hello <span id="my-demo">2nd December 2019!</span></h1>
<button onclick="myFunction()">Click me</button><br>
<img src="https://www.dropbox.com/s/2965glxbyqjmi9h/SanTi.jpg?raw=1"></div>
</body>
</html>
           

error.html

<html><body><h1>There has been an error for Xiong's website!</h1></body></html>
           

建立一個S3 Bucket,取名為:

xionglambdatest

,在

Properties

下面進行設定,

Static website hosting

,建立了以下Endpoint,

Index document

設定為

index.html

Error Document

設定為

error.html

,儲存。

Static website hosting

Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

将前面建立的

index.html

error.html

進行上傳,

如果你注冊了域名的話,可以使用Route53來設定 A Record來指向S3 Bucket的Endpoint達到域名通路的目的。

這裡直接測試:

Static website hosting

Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

傳回以下錯誤:

403 Forbidden
Code: AccessDenied
Message: Access Denied
RequestId: 0264A5A5BC4FBDE3
HostId: r03Yr+l5vDDiR/0YQL8if2qmRP1lBvBzLoeoGgw6z3jec8XnyWJsz790UwmZGI49ejY5QFYWrfE=
An Error Occurred While Attempting to Retrieve a Custom Error Document
Code: AccessDenied
Message: Access Denied
           

在S3 Bucket

xionglambdatest

中,設定

Make Public

,确認,再試,可以成功通路。

點按鈕無反應,在Chrome的Develop Tool裡發現碰到以下錯誤:

Access to XMLHttpRequest at 
'https://byaaiuzpad.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI' 
from origin 'http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource.
           

CORS在作怪,在

Resource

下裡的

Action

裡點

Enable CORS

,再試, 點按鈕後,界面傳回如下:

Hello {"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, 
"body": "Xiong Huilin"}
           

說明

https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

傳回了

{"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, "body": "Xiong Huilin"}

重新再試,在建立

GET

方法時,記得把

Use Lambda Proxy integration

選擇項選上, 表明是Lambda傳回值 。另外記得在

Resource

下裡的

Action

裡點

Enable CORS

, 最後

Deploy API

。這次成功。

點按鈕後,以下文字:

Hello 2nd December 2019!

變為:

Hello Xiong Huilin

也就是

https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

傳回了

Xiong Huilin

,測試成功!

點完按鈕的效果如下:

AWS API Gateway和Lambda的簡單測試具體流程建立Lambda應用建立API GatewayS3 Bucket網頁測試觸發API Gateway和Lambda函數碰到S3 Bucket删除問題術語Reference

碰到S3 Bucket删除問題

前面做Elastic Beanstalk測試的時候:AWS的CloudFormation和Elastic Beanstalk的簡單測試,自動建立了名為

elasticbeanstalk-ap-southeast-1-606255748358

的S3 Bucket,删除時傳回了

Access Denied

的錯誤。

參見: AWS Forum: can’t delete empty elasticbeanstalk created bucket

在以下Bucket Policy的JSON檔案裡将

Deny

改成

Allow

,就可以删除了,問題解決。

{
            "Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:DeleteBucket",
            "Resource": "arn:aws:s3:::elasticbeanstalk-ap-southeast-1-606255748358"
        }
           

參見Bucket Policy Examples,可以使用以下JSON檔案設定

Bucket Policy

以達到Bucket為公共通路的目的:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::xionglambdatest/*"
        }
    ]
}
           

術語

Lambda:參見什麼是 AWS Lambda?

REST:參見Representational_state_transfer 維基

Reference

Lambda Troubleshooting - Acloudguru

什麼是 AWS Lambda?

Representational_state_transfer 維基

AWS的CloudFormation和Elastic Beanstalk的簡單測試

AWS Forum: can’t delete empty elasticbeanstalk created bucket

ACloud Guru

Bucket Policy Examples

繼續閱讀