AWS Lambda是AWS于2014年推出的一项计算服务,通过 AWS Lambda,无需预置或管理服务器即可运行代码。您只需按使用的计算时间付费 – 代码未运行时不产生费用。借助AWS Lambda,几乎可以为任何类型的应用程序或后端服务运行代码,而且无需执行任何管理。AWS Lambda是在可用性很高的计算基础设施上运行代码,执行计算资源的所有管理工作,包括服务器和操作系统维护、容量预置和自动扩展、代码监控和记录。
创建Lambda函数
为了使用 AWS Lambda 我们首先需要导出一个函数做处理函数例如 node
export handler = () => {
console.log('Hello world')
}创建Lambda的所需要的配置文件
AWSTemplateFormatVersion: 2010-09-09Description: hello world
Transform: AWS::Serverless-2016-10-31
Parameters: #外部传进来的参数
Environment:
Type: String
SourceBucket:
Type: String
Service:
Type: String
Resources:
HelloWorldRole: #lambda所用的角色
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
RoleName: !Sub HelloWorld-${Environment}
Policies:
- PolicyName: !Sub BaisonNavBetweenStoresCreateOrderPolicy
PolicyDocument:
Version: 2012-10-17
Statement: #配置该lambda可以调用aws sqs的服务
- Effect: Allow
Action:
- sqs:*
Resource: '*'
HelloWorld: #创建lambda的配置文件
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub HelloWorld-${Environment}
Handler: index.handler #函数的入口
Runtime: nodejs8.10
CodeUri: ../../lambda #放代码的路径
Description: Hello World
Role: !GetAtt HelloWorldRole.Arn #这个lambda的角色的arn
Timeout: 900 #运行时间,最多少运行15分钟
Environment: #环境变量
Variables:
Region: eu-west-1cloudFormation自动化部署
这里使用的是Makefile批量执行命令
upload-lambda-to-s3 = @echo "\n----- Building Lambda Backend function START -----\n" && \
mkdir -p cfDist/test && \
aws cloudformation package \ #使用cloudformation打包本地配置文件
--template-file cloudFormation/test/helloWorld.yaml \ #本地配置文件
--output-template-file cfDist/test/cfServerlessTemplate.yaml \ #生产后的配置文件
--s3-prefix test \ # 配置文件放在s3的文件路径
--s3-bucket helloWorld && \ # 配置文件所存放的s3
echo "\n----- Build Lambda Backend function DONE -----\n"
deploy-lambda = @echo "\n----- Deploying Lambda functions START -----\n" && \ date && \
aws cloudformation deploy \ #部署 cloudformation
--no-fail-on-empty-changeset \ #只会部署有更改的文件
--template-file cfDist/test/cfServerlessTemplate.yaml \
--stack-name helloWorld \ #cloudformation 堆栈的名字
--capabilities CAPABILITY_NAMED_IAM \
--region eu-west-1 \ # 区域
--parameter-overrides \ #传进yaml文件的参数
Service= pin \
SourceBucket= helloWorld\
Environment= dev && \ date && \
echo "\n----- Deploying Lambda functions DONE -----\n"按顺序执行以下命令
make upload-lambda-to-s3 make deploy-lambda就可以创建一个aws lambda了
结尾
第一次写这种文章,这单纯就是记录下工作用到的技术,不知道有没有大佬对aws感兴趣可以一起讨论下,后续会继续出SQS, S3, DynamoDB, SSM, ApiGateway...还有更多的 AWS相关的服务