AWS Lambda LAB2
本次Lambda LAB2 練習 搭配 AWS API Gateway, 主要是Clients 送出一個 request 由AWS API Gateway 代理觸發對應的 Lambda function,Lambda 取得Client IP ,及藉由GeoIP 查找IP 的 Country_code,最後運算完成結果丟回給 API Gateway,最終API Gateway 回應結果給 Clients。如下示意圖:
圖片來源: API Gateway 入門
封裝Pyhton code
使用zip 檔封裝Python code
有個目錄名為 myip , 有以下檔案:
1 | myip |
lambda_function.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import json
from geoip import open_database
GeoipDataBase="GeoLite2-Country.mmdb"
dbip=open_database(GeoipDataBase)
def getcountry(ip):
chkip=getattr(dbip.lookup(ip),'country',None)
if chkip:
return chkip
else:
return 'NO_Country'
dbip.close()
def lambda_handler(event, context):
# TODO implement
print("FirstProcess: get Header")
message={}
message['xForwardfor']=event['headers']['x-forwarded-for']
message['myIP']=event['requestContext']['http']['sourceIp']
message['myCountry']=getcountry(message['myIP'])
return {
'statusCode': 200,
'body': json.dumps(message,sort_keys=True, indent=4, separators=(',', ': '))
}GeoLite2-Country.mmdb : 可以到 Maxmind 下載 mmdb
lambda_function.py 有引用 Python 第三方模組 geoip , 此模組套件名稱為 python-geoip-python3,並安裝到新 package
目錄
,將package 封裝為zip 壓縮檔 , 檔名為: deploy_lambda_myip.zip
1 | cd myip |
將 原先myip目錄底下兩個檔案 GeoLite2-Country.mmdb , lambda_function.py 封裝到 deploy_lambda_myip.zip
1 | cd myip |
上傳 deploy_lambda_myip.zip
建立Lambda 名為 lambdaLAB2
Runtime 選擇 Python3.9
CPU 架構選擇 : arm64 (封裝Python code 於 MacBook Air M1下執行的 )
於右邊點選 上傳於 zip
上傳成功後,於左邊可以看到幾個檔案(geoip.py, GeoLite2-Country.mmdb, lambda_function.py)
建立 API Gateway
AWS Lambda 是屬於事件式 Function運算資源, 需要有一個觸發事件去啟動 Lambda。這個 LambdaLAB2 主要呈現像 Web App一樣; Client 端 送出一個 request 事件請求給 API Gateway, API Gateway再依據此事件去調用 Lambda, Lambda 運算完的結果傳給 API Gateway,最後response 給 Client。
於aws console management 搜尋欄 打上 key word: api , 選擇 API Gateway
開始建立API: 選擇 HTTP API 類型
新增整合: 選擇 Lambda
AWS 區域: us-east-1 (lambdaLab2 是建立在此區域)
Lambda 函數 : 自動會帶出剛建立Lambda ID 尾碼是lambdaLAB2
設定路由 : 方法 get (request) , 資源路徑: / , 整合目標: lambdaLAB (API Gateway 調用目標)
生成一個 叫用 url
於Client 端 Browser 測試 叫用 url