bash-lambda-layer Run Bash scripts in AWS Lambda v开源项目

我要开发同款
匿名用户2021年11月09日
49阅读
开发技术SHELL
所属分类终端/远程登录、应用工具
授权协议MIT License

作品详情

BashinAWSLambdaNOLONGERSUPPORTED

Thisrepositoryandlayerisnolongerreceivingupdatesorsupport.I'vebeentoobusytokeepupwithchangesintheLambdaenvironmentandthishasfallenbehind.Useatyourownrisk.

RunBashinAWSLambdaviaLayers.ThisLayeris100%BashandhandlesallcommunicationwiththeLambdaRuntimeAPI.ThisallowsyoutorunfullBashscriptsandcommandsinsideofAWSLambda.ThisLayeralsoincludescommonCLItoolsusedinBashscripts.

SeetheHowTosectiontounderstandhowtousetheselayers.Alsoseetheexample-basic.shfileforanexampleofhowtowriteaBashscriptcompatiblewiththisLayer.

ARNarn:aws:lambda:<region>:744348701589:layer:bash:8HowToGettingStartedAWSLambdaConsoleLogintoyourAWSAccountandgototheLambdaConsole.CreateanewfunctionandgiveitanameandanIAMRole.Forthe"Runtime"selection,selectUsecustomruntimeinfunctioncodeorlayer.Inthe"Designer"sectionofyourfunctiondashboard,selecttheLayersbox.Scrolldowntothe"ReferencedLayers"sectionandclickAddalayer.SelecttheProvidealayerversionARNoption,thencopy/pastetheLayerARNforyourregion.ClicktheAddbutton.ClickSaveintheupperright.UploadyourcodeandstartusingBashinAWSLambda!AWSCLICreateafunctionthatusestheprovidedruntimeandtheLayerARNforyourregion.$awslambdacreate-function\--function-namebashFunction\--rolebashFunctionRole\--handlerindex.handler\--runtimeprovided\--layersarn:aws:lambda:<region>:744348701589:layer:bash:8\--zip-filefileb://function.zipStartusingBashinAWSLambda!UpdatingVersionsAWSLambdaConsoleInthe"Designer"sectionofyourfunctiondashboard,selecttheLayersbox.Scrolldowntothe"ReferencedLayers"sectionandclickAddalayer.SelecttheProvidealayerversionARNoption,thencopy/pastetheLayerARNforyourregion.ClicktheAddbutton.Stillunderthe"ReferencedLayers"section,selectthepreviousversionandclickRemove.ClickSaveintheupperright.AWSCLIUpdateyourfunction'sconfigrationandaddtheLayerARNforyourregion.$awslambdaupdate-function-configuration\--function-namebashFunction\--layersarn:aws:lambda:<region>:744348701589:layer:bash:8WritingScripts

LikeanyotherLambdafunctioncode,yourmainscript'snamemustmatchthefirstpartofyourhandler.Insideyourmainscript,youmustdefineafunctionthatmatchesthesecondpartofthehandler.Youmusthaveset-ebethefirstlineinsideyourfunction.Putting#!/bin/bashatthetopofyourfileisnotnecessary.SoifyourLambdahandlerisindex.handler,yourfileandcontentsshouldlooklike:

$catindex.shhandler(){set-e...}

Theeventdataissenttoyourfunctionasthefirstparameter.Toaccessit,youshoulduse$1.Soifyouneedtheeventdata,youshouldsetittoavariable.Forexample,EVENT_DATA=$1.

handler(){set-eEVENT_DATA=$1}

Allthepre-installedtoolsarealreadyinyour$PATHsoyoucanusethemasexpected.AnycommandoutputisautomaticallysenttoCloudWatch,justlikenormalLambdafunctions.

handler(){set-eEVENT_DATA=$1awss3ls$(echo$EVENT_DATA|jq."bucket")}

Ifyouneedtosendaresponseback,youshouldsendtheresponsetostderr.(seetheCaveatssectionforanexplanation)Tosendoutputtostderryoushoulduse>&2.ThiswillbepickedupandreturnedfromtheLambdafunction.

handler(){set-eEVENT_DATA=$1awss3ls$(echo$EVENT_DATA|jq."bucket")echo"{\"success\":true}">&2}Caveats

Bashbehavesinwaysunlikeotherprogramminglanguages.Assuch,therearesomerequirementsontheuser'sendthatmustbedone.

set-emustbesetinsideyourfunction

Bydefault,abashscriptwon'texitwhenitencountersanerror.Inorderforthelayertocorrectlycatchtheerrorandreportit(aswellasstopthescriptfromexecuting),wemustsetthefunctiontoexitonerror.

Youmustsendyourreturnvaluetostderr

InsideanormalBashfunction,anythingthatissenttostdoutispartofthereturnvalueforthatfunction.Inordertoproperlycapturetheuser'sreturnvalueandstillsendstdouttoCloudWatch,thisLayerusesstderrasthereturnvalue.Tosendsomethingtostderrsimplyappend>&2totheendofthecommand.Seetheexamplescriptsforhelp.

Notes

$HOMEissetto/tmp.ThisisbecausetheLambdafilesystemisread-onlyexceptforthe/tmpdirectory.Someprogramsrequire$HOMEtobewriteable(liketheAWSCLIandsomeSSHcommands),sothisallowsthemtoworkwithoutissue.

FilestoconfiguretheAWSCLIshouldbeputin/tmp/.aws.Bydefault,theCLIusesthesameregionandIAMRoleasyourlambdafunction.Ifyouneedtosetsomethingdifferent,youcanusethe/tmp/.aws/configand/tmp/.aws/credentialsfilesaccordingly.

Whenusingcurl,youshouldusethe-sflag.Withoutthesilentflag,curlwillsendtheprogressbarofyourrequesttostderr.Thiswillshowupinyourresponse.Soit'susuallybesttodisabletheprogressbar.

TheAWSCLIappearstobemuchslowerthanmostoftheAWSSDKs.TakethisintoconsiderationwhencomparingBashwithanotherlanguageandevaluatingexecutiontimes.

Ifacommandisloggingunwantedmessagestostderrthatarebeingpickedupinyourresponse,youcanseeifthereissomethingsimiliartoa--silentflag.Ifthereisnot,youcanremovethemessagestostderrbyredirectingto/dev/null(2>/dev/null)orredirectingstderrtostdoutforthatcommand(2>&1)tosendthemtoCloudWatch.

Withthismethodthereisnocontextinthefunction,onlyeventdata.Theeventdataissenttoyourfunctionasthefirstparameter.Sotoaccesstheeventdata,use$1,forexampleEVENT_DATA=$1.Inordertogivesomedetailsthatwereavailabeinthecontext,Iexportafewadditionalvariables.

AWS_LAMBDA_REQUEST_ID-AWSLambdaRequestID

AWS_LAMBDA_DEADLINE_MS-Time,inepoch,thatyourfunctionmustexitby

AWS_LAMBDA_FUNCTION_ARN-FullAWSLambdafunctionARN

AWS_LAMBDA_TRACE_ID-Thesamplingdecision,traceID,andparentsegmentIDofAWSXRay

Building

Tobuildalayer,simplyrunmakebuild.Thiswillcreateaziparchiveofthelayerintheexport/directory.

Publishing

Topublishthelayertothepublic,simplyrunmakepublish.Thiswillcreateanewversionofthelayerfromtheexport/layer.zipfile(createfromtheBuildstep)andgiveitaglobalreadpermission.

AddingNewExecutables

Someexecutablesareabletorunbythemselvesandsomerequireadditionaldependenciesthatarepresentontheserver.It'shardtocoverherecasehere,butiftheexecutablerunbyitselfitcaneasilybeadded.Ifithasdependencies,youmustexplorewhatthosedependenciesareandhowtoaddthemtothelayeraswell.

YoucaneitheraddtheexecutablefromanAmazonLinuxAMIorfromthelambci/lambda:build-python3.6Dockerimage.

Disclaimer:Iusuallydon'taddinexecutablesfrompullrequestsforsecurityreasons.IfyouwouldliketoseeanexecutableinthislayermakeanissueandI'lltrytoaddit.

IncludedExecutables$aws$bc$git$jq$rsync$scp$sftp$ssh$sshpass$time$traceroute$tree$wget$vim$zip$unzip

AlreadyincludedintheLambdaenvironment:

$awk$cat$curl$cut$date$diff$grep$gzip$head$md5sum$pwd$sed$tar$tail$tee$xargs

Ifyouwouldliketoseemore,pleasecreateanissue.

Shout-outtotheLambCIteamfortheirworkonlambci/git-lambda-layerwhichsomeofthegitandsshbuildprocesswastakenfrom.

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论