自從學會lambda
之後,都會使用它來執行一些python
爬蟲的功能
但一直都是打包好zip
檔後進到Console去點來點去
這次有嘗試著利用aws cli
去做完整套流程(超複雜,邊下指令邊碎念)
直接來Demo
打包這一段基本上就是利用zip
來做
#step 1 : go to site-package folder and compress all
~$ cd /your/python/site-package/path/
~$ zip -9r *
#step 2 : go to your code path and compress it
~$ cd /your/code/path
~$ zip -9r yourcode.py
打包好後就可以上傳啦
aws lambda create-function --function-name 'FunctionName' --zip-file fileb:///your/zip/path/filename.zip --handler pyfilename.function_handler --runtime python3.7 --timeout 30 --role arn:aws:iam::222333999000:role/service-role/blahblah
等待上傳後可以下aws lambda list-functions
或aws lambda get-function
來確認有沒有上傳
不過建議用第二個,因為如果有很多Lambda
在上面,會看很久
aws lambda list-functions
aws lambda get-function --function-name FunctionName
然後要來建立一個cloudwatch events
aws events put-rule --name 'EventName' --schedule-expression 'cron(55 15 * * ? *)' --state 'ENABLED' --description 'do something at every 23:55'
基本上應該不用解釋太多,頂多要注意的是他的cron
有一點不一樣,可參照官方說明
再來我們要新增權限給Lambda
aws lambda add-permission --function-name FunctionName --action 'lambda:InvokeFunction' --principal events.amazonaws.com --statement-id event-trgger --source-arn arn:aws:events:us-east-1:222333999000:rule/EventName
這邊要注意的只有statement-id
這個,這必須是唯一的值
最後就把events targets
指定給Lambda
aws events put-targets --rule EventsName --targets '{"Id":"1","Arn":"arn:aws:lambda:us-east-1:222333999000:function:FunctionName"}'
如此一來,Lambda
就會在每天晚上11:55分去執行了。
如果有看不清楚的地方,可以看這邊參考官方說明