Skip to content

Latest commit

 

History

History
executable file
·
375 lines (261 loc) · 12.9 KB

helper_AWS-Lambda.md

File metadata and controls

executable file
·
375 lines (261 loc) · 12.9 KB

GitHub license GitHub stars GitHub forks GitHub issues GitHub watchers

Run code without thinking about servers or clusters

一般我們寫程式,都是稱為 application,而 Lambda 是稱為 function.

1.1. How it works

A. File processing

aws_lambda01

B. Stream processing

aws_lambda01

C. Web applications

aws_lambda01

D. IoT backends

aws_lambda01

E. Mobile backends

aws_lambda01

2. Sample

2.1. Hello world (on console)

2.1.1. Create and Execution

A. Sign in as IAM user

Account ID (12 digits) : 123456789012

請先登入 https://123456789012.signin.aws.amazon.com/console

aws_lambda021

aws_lambda022

C. Create function

aws_lambda023

C.1. index.js
console.log('Loading function');

exports.handler = async (event, context) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));
    console.log('value1 =', event.key1);
    console.log('value2 =', event.key2);
    console.log('value3 =', event.key3);
    return event.key1;  // Echo back the first key value
    // throw new Error('Something went wrong');
};
C.2. lambda_function.py
import json

print('Loading function')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))
    print("value1 = " + event['key1'])
    print("value2 = " + event['key2'])
    print("value3 = " + event['key3'])
    return event['key1']  # Echo back the first key value
    #raise Exception('Something went wrong')

D. create a test event - SAVE / TEST

aws_lambda024

E. Execution result

aws_lambda025

2.1.2. CloudWatch

特別注意,在 CloudWatch 中傳遞的 event 都是用 '字串'。

一般 JSON都是使用 "字串"

aws_cloudwatch010

2.1.3. IAM

aws_iam011

這邊不幫忙演示其操作。請閱讀內部的 README.md。

3. How to Become a AWS Lambda Collaborator

先從一個簡單的程式開始。學會部署第一隻程式至 Lambda。 因為部署的方式很多種,至於學習那一種,就要看自己的選擇。

flowchart TD
	Start([Start])
	01_HelloLambda[/01_HelloLambda/]
	layer[create layer]
	s3[/s3://bucket/stack/]
	subgraph CloudFormation
 		stack[Stack - LambdaHello]
 	end	
	subgraph Lambda
 		LambdaHello[Function - LambdaHello]
 	end	
  End([End])
	
	Start-->01_HelloLambda-->layer
	layer-->|aws cloudformation package|s3-->|aws cloudformation deploy|stack-->LambdaHello-->End

A. 學習目標

A.1. Deploy 部署

這邊透過 CloudFormation 進行部署。

A.2. 撰寫 Makefile

建議使用 Makefile,可以建立depend 的關係。Shell Script 感覺會比較混亂。

A.3. Run on local

在 Deploy 前,記得在本地端執行。

A.4. Debug by CloudWatch

deploy 之前記得在 Local 執行,查看相關 log messages。部署後也要再從 CloudWatch 中確認。

aws_cloudwatch011 aws_cloudwatch012 aws_cloudwatch013

3.2. Handle event, context

新增 event.json 和模擬參數傳遞

flowchart LR
	Start([Start])
	event[/event.json/]
	subgraph Lambda
 		LambdaHello[LambdaHello]
 	end	
  End([End])
	
	Start-->event-->|event, context|LambdaHello
	Lambda-->End

3.3. Lambda and S3

已經知道擺放程式和參數傳遞之後,就是要學習怎麼亙動。(Tutorial: Using an Amazon S3 trigger to invoke a Lambda function) 本範例:

  1. 上傳檔案至 s3://lambdax9
  2. Trigger function - LambdaHello
  3. 將檔案複製至 s3://lambdax9bak
flowchart LR
	Start([Start])
	project[/project.json/]
	subgraph Lambda
 		LambdaHello[LambdaHello]
 	end	
	subgraph S3
		lambdax9[s3://lambdax9]
		lambdax9bak[s3://lambdax9bak]
	end
  End([End])
	
	Start-->project-->|push|lambdax9
	lambdax9-->|trigger|LambdaHello
  LambdaHello-->|copy project.json|lambdax9bak
	lambdax9bak-->End

aws_lambda031 aws_lambda032

A. 學習目標

A.1. Create Trigger

這邊用 S3 當範例,因為 S3 裏的檔案變動,利用 aws cli 就可以了。

$ S3_BUCKET_NAME=lambdax9bak; aws-ls
$ S3_BUCKET_NAME=lambdax9; aws-ls
$ S3_BUCKET_NAME=lambdax9; aws-push out.yml
$ S3_BUCKET_NAME=lambdax9; aws-rm out.yml

3.4. Deploy Lambda Function and S3 trigger (一鍵部署)

之前已經學會 deploy,前段也用 Console 設定了相關 Trigger ,那為什麼還要進行這章節。 主要是希望把整個流程和程式當成一個專案進行部署。不知各位在公司定版時,進行程式部署時,是否還要一個員工,這個 Console 按按,那個 Console 按按。

總會有人挑戰我,你只會 S3 哦,其它呢?其它呢?

我又不是 AWS 專家,也不是它們的員工,我也是做中學,學中做。

A. 學習目標

A.1. 一鍵部署

當所有的步驟達到“一鍵部署”之後,才有可能進行下一步“自動部署”。

A.2. 一鍵刪除部署

記住 AWS 所有的東西都要錢;部署後,一定會忘了曾經做過什麼,所以學會“一鍵部署“是很重要的,而“一鍵刪除部署”更是能解決不需要的燒錢功能。

B. YAML (.yml)

這真的是一個大問題,網路上找了 10 來個範例,能用的只有一個。 學會寫好一個 YAML 很難,可能比寫程式還難。

# 雖然可以驗證,但是可用度不高
$ aws cloudformation validate-template \
		--template-body file://$(TEMPLATE_FILE)

# 從這邊滙出來的,跟 CloudFormation 有差別
$ aws s3api get-bucket-notification-configuration \
	--bucket lambdax9 --output yaml

3.5. Deploy Lambda Function DynamoDB trigger (一鍵部署)

將 3.3. Lambda and S3 部署後,新加入一個 DynamoDB trigger。

試著記錄相對應的 event ,就可進行一鍵部署。

flowchart LR
	Start([Start])
	project[/project.json/]
	subgraph Lambda
 		LambdaHello[LambdaHello]
 	end	
	subgraph DynamoDB
		Music[TableName: Music]
		MusicBak[TableName: MusicBak]
	end
  End([End])
	
	Start-->project-->|push|Music
	Music-->|trigger|LambdaHello
  LambdaHello-->|copy item|MusicBak
	MusicBak-->End

aws_lambda033

A. 學習目標

A.1. Policies

這邊需要調用 DynamoDB,所以要開啟相關權限。所以 YAML 的設定很重要。

AmazonDynamoDBFullAccess

A.2. Create Trigger

試著觸發 Trigger,然後至 CloudWatch 查看 Log,將裏面的 event 抓取出來。

aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'No One You Know','SongTitle':'Call Me Today', 'AlbumTitle':'Somewhat Famous', 'Awards':'1'}"

aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'No One You Know','SongTitle':'Howdy', 'AlbumTitle':'Somewhat Famous', 'Awards':'2'}"

aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'Acme Band','SongTitle':'Happy Day', 'AlbumTitle':'Songs About Life', 'Awards':'10'}"
                            
aws dynamodb execute-statement --statement "INSERT INTO Music  \
                VALUE  \
                {'Artist':'Acme Band','SongTitle':'PartiQL Rocks', 'AlbumTitle':'Another Album Title', 'Awards':'8'}"
                

B. YAML (.yml)

很難寫,因為不好 Debug。

Appendix

I. Study

Lambda 這部分,基本上都是用範例來學習,很少閱讀官方的文件。

II. Debug

II.1. An error occurred (ValidationError) when calling the CreateChangeSet operation: Stack:arn:aws:cloudformation:eu-west-1:123456789012:stack/blank520/5270ab20-d557-11ed-afb2-0a14943d5521 is in ROLLBACK_COMPLETE state and can not be updated.

# 修改 region
$ vi ~/.aws/config
region =

II.2. json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 2 (char 3)

python json.load 時發生此問題時,to replace ' -> "

III. Glossary

AI, Artificial Intelligence

人工智慧 (AI) 是電腦科學的一個領域,致力於解決與人類智慧相關的常見認知問題,例如學習、解決問題和模式辨識。人工智慧 (通常簡稱為 "AI") 呈現出機器人或未來世界的景像,也就是說,AI 不再是科幻小說中虛構的機器人,而真正成為現代高階電腦科學中的現實。

CSAT是顧客滿意度得分的簡稱。它是商業上經常使用的一個指標,在所有類型的企業中,都可以以CSAT作為客戶服務和產品質量的關鍵績效指標。雖然顧客滿意度是一個籠統的概念,但CSAT可以將其轉化成更明確的指標,以百分比表示。例如,100%是非常好的,而0%則是非常糟糕的。

ML, Machine Learning

是一項用於建立機器學習模型並產生預測結果的受管服務,可協助開發穩定且可擴展的智慧應用程式。

IV. Tool Usage

Author

Created and designed by Lanka Hsu.

License

HelperX is available under the BSD-3-Clause license. See the LICENSE file for more info.