这就是如何使用cloudformation部署AWS Lambda函数

By IOD Expert Matt Billock

IOD专家Matt Billock

AWS Lambda is a powerful tool for developing serverless applications and on-demand workflows. However, this power comes at a cost in terms of flexibility and ease of deployment, as the manual deployment process that AWS Lambda recommends can be error-prone and hard to scale.

AWS Lambda是用于开发无服务器应用程序和按需工作流的强大工具。 但是,这种能力的代价是灵活性和易于部署,因为AWS Lambda建议的手动部署流程容易出错并且难以扩展。

CloudFormation revolutionizes this process, replacing copied zip files with dependable and repeatable template-based deployment schemes. With CloudFormation, your Lambda functions will be easier to maintain, easier for your developers to understand, and easier to scale as your application grows.

CloudFormation彻底改变了这一过程, 将复制的zip文件替换为可靠且可重复的基于模板的部署方案。 借助CloudFormation,您的Lambda函数将更易于维护,更易于开发人员理解以及随着应用程序的扩展而易于扩展。

查看AWS Lambda部署 (Reviewing AWS Lambda Deployments)

AWS Lambda function deployments are based around file handling — namely, by zipping your code into an archive and uploading the file to AWS. At its core, all AWS Lambda functions follow this pattern:

AWS Lambda功能部署基于文件处理,即通过将代码压缩到存档中并将文件上传到AWS。 本质上,所有AWS Lambda函数都遵循以下模式:

Create a zip file. Upload to an S3 bucket. Set the function to active.

创建一个zip文件。 上载到S3存储桶。 将功能设置为**。

This takes place whether you’re manually deploying the code, have outsourced your deployments to a tool, or are following any protocol in-between.

无论您是手动部署代码,将部署外包到工具中还是遵循两者之间的任何协议,都会发生这种情况。

Once the file is received, AWS unzips your code into the appropriate folder structure, making it available to run when the Lambda container is spun up. This approach is a key point to remember as we discuss Lambda deployments and also exposes one of the first holes in the manual deployment process — AWS Lambda functions have an unstated structure that you need to follow.

收到文件后,AWS会将您的代码解压缩到适当的文件夹结构中,以使其在启动Lambda容器时可以运行。 在讨论Lambda部署时,此方法是要记住的关键点,并且还暴露了手动部署过程中的第一个漏洞– AWS Lambda函数具有未声明的结构,需要遵循。

Simply put, you do not want to right-click on a file and create an archive; otherwise, you’ll encounter an error when you try to run your deployed Lambda code. The following screenshots illustrate this issue:

简而言之,您不想在文件上单击鼠标右键并创建一个存档。 否则,当您尝试运行已部署的Lambda代码时会遇到错误。 以下屏幕截图说明了此问题:

If you examine the zip files produced by the above method, you’ll find that their root level consists of your code folder:

如果检查通过上述方法生成的zip文件,您会发现它们的根目录由您的代码文件夹组成:

这就是如何使用cloudformation部署AWS Lambda函数

The issue this introduces is specifically related to how AWS Lambda deploys the code — namely, it simply unzips the provided code archive to an executable folder, then routes invocation requests to the application code found in that folder. When you provide a zip archive with a folder at the root level, instead of the application code itself, AWS Lambda has no idea what to do and throws errors. So, make sure that you zip the folder contents themselves, as follows:

此问题特别与AWS Lambda部署代码的方式有关-即,它只是将提供的代码存档解压缩到可执行文件夹中,然后将调用请求路由到该文件夹​​中找到的应用程序代码。 当您为zip归档文件提供根目录下的文件夹而不是应用程序代码本身时,AWS Lambda不知道该怎么办并引发错误。 因此,请确保您自己压缩文件夹内容,如下所示:

这就是如何使用cloudformation部署AWS Lambda函数

When you do this, your code is put at the root level of the zip folder. This allows AWS Lambda to easily deploy your published code:

执行此操作时,您的代码将放在zip文件夹的根目录下。 这样,AWS Lambda可以轻松部署您发布的代码:

这就是如何使用cloudformation部署AWS Lambda函数

Each Lambda function exists independently, meaning that you cannot easily share resources between Lambda functions — shared libraries, source data files, and all other information sources that need to be included with the zip archive you upload. This additional fragility and duplication can be resolved with Lambda layers. Lambda layers provide you with a common base for your functions, letting you easily deploy shared libraries without the duplication that would be required when using only the base container.

每个Lambda函数都独立存在,这意味着您无法轻松地在Lambda函数之间共享资源-共享库,源数据文件和所有其他需要包含在上载的zip存档中的信息源。 这种额外的脆弱性和重复性可以通过Lambda层解决。 Lambda层为您提供了功能的通用基础,使您可以轻松部署共享库,而无需仅使用基础容器时就需要进行重复。

While you can set up a scriptable and maintainable deployment process, once the project size grows, the brittleness of the above steps will quickly become apparent. AWS CloudFormation solves this very complexity problem by categorizing infrastructure as code; this lets your developers and development operations teams create, deploy, and tear down resources with simple configuration-file modifications. These configuration files are human-readable and can be modified in any text configuration, programming language, or UI tools that you desire.

尽管您可以设置一个可编写脚本且可维护的部署过程,但是一旦项目规模增大,上述步骤的脆弱性将很快变得明显。 AWS CloudFormation通过将基础架构归类为代码来解决此非常复杂的问题。 这使您的开发人员和开发运营团队可以通过简单的配置文件修改来创建,部署和拆除资源。 这些配置文件是人类可读的,可以使用所需的任何文本配置,编程语言或UI工具进行修改。

Furthermore, CloudFormation lets you centralize the deployment of your infrastructure, creating a build process for your serverless functions that is both repeatable and predictable.

此外,CloudFormation使您可以集中化基础架构的部署,为可重复且可预测的无服务器功能创建构建过程。

使用CloudFormation改善Lambda部署 (Improving Lambda Deployments with CloudFormation)

Moving from the error-prone manual process of Lambda deployment to the superpowered CloudFormation model is a straightforward process of translating your function’s infrastructure needs into the appropriate CloudFormation template language. CloudFormation lets you then consolidate the disparate resource deployments for your application into a small set of configuration files, allowing your infrastructure to be maintained alongside your application code.

从容易出错的Lambda部署手动过程过渡到功能强大的CloudFormation模型,这是一个将函数的基础架构需求转换为适当的CloudFormation模板语言的简单过程。 然后,CloudFormation使您可以将应用程序的不同资源部署整合到一小组配置文件中,从而可以与应用程序代码一起维护基础架构。

All in all, CloudFormation makes deploying AWS Lambda functions incredibly simple.

总而言之,CloudFormation使部署AWS Lambda函数非常简单。

Start by creating the template file that will define your resources. This will be your working folder for your code. Next, create your function in the appropriate file for your desired Lambda runtime. Finally, create an S3 bucket and provide its address to your Lambda function; once you’ve done this, you can deploy functions simply by copying your zip file to the correct S3 bucket.

首先创建将定义资源的模板文件。 这将是您的代码的工作文件夹。 接下来,在所需的Lambda运行时的适当文件中创建函数。 最后,创建一个S3存储桶,并将其地址提供给Lambda函数; 完成此操作后,只需将zip文件复制到正确的S3存储桶中即可部署功能。

CloudFormation will be the tool that ties together all the resources your function requires. In CloudFormation, you will define the function, the function’s IAM role, the function’s code repository in S3, and execution policies to ensure that your function can do everything it needs to do within the AWS ecosystem. CloudFormation further gathers these resources together, centralizing all of your infrastructure definitions in a single template file that lives alongside your code.

CloudFormation将是将功能所需的所有资源联系在一起的工具。 在CloudFormation中,您将定义功能,功能的IAM角色,S3中的功能的代码存储库以及执行策略,以确保您的功能可以在AWS生态系统中完成所需的一切。 CloudFormation进一步将这些资源收集在一起,将所有基础结构定义集中在一个与代码一起存在的模板文件中。

通过示例部署运行 (Running Through a Sample Deployment)

In this section, we’ll run through a quick example of creating a CloudFormation-driven deployment process for an AWS Lambda function. Start with the following Node.JS code to create a simple Lambda function using the nodejs12.x runtime:

在本节中,我们将通过一个快速示例为AWS Lambda函数创建一个CloudFormation驱动的部署流程。 从下面的Node.JS代码开始,使用nodejs12.x运行时创建一个简单的Lambda函数:

exports.handler = async (event) => {

exports.handler = async (event) => {

// TODO implement

// TODO implement

const response = {

const response = {

statusCode: 200,

statusCode: 200,

body: JSON.stringify('CloudFormation deployment

body: JSON.stringify('CloudFormation deployment

successful!'),

successful!'),

};

};

return response;

return response;

};

};

This code is deliberately simple, allowing you to highlight the deployment process itself. Once you’ve created the function code, you can begin creating all of the items that will allow you to deploy and run the code with CloudFormation.

该代码故意简单,可让您突出显示部署过程本身。 一旦创建了功能代码,就可以开始创建所有项目,这些项目将允许您使用CloudFormation部署和运行代码。

First, create a new file in the same directory as the function. These instructions assume that your file will be named template.yml. Once you‘ve created the empty template file, start including resources needed to get your function running. You can begin with defining an S3 bucket to hold your function code:

首先,在与函数相同的目录中创建一个新文件。 这些说明假定您的文件将被命名为template.yml。 创建空模板文件后,开始包括使函数运行所需的资源。 您可以先定义一个S3存储桶来保存您的功能代码:

AWSTemplateFormatVersion: '2010-09-09'

AWSTemplateFormatVersion: '2010-09-09'

Description: 'Example Lambda zip copy'

Description: 'Example Lambda zip copy'

LambdaZipsBucket:

LambdaZipsBucket:

Type: AWS::S3::Bucket

Type: AWS::S3::Bucket

Then, create the resources needed for your function, including an IAM role and the function definition itself:

然后,创建功能所需的资源,包括IAM角色和功能定义本身:

MyFunctionRole:

MyFunctionRole:

Type: AWS::IAM::Role

Type: AWS::IAM::Role

Properties:

Properties:

AssumeRolePolicyDocument:

AssumeRolePolicyDocument:

Version: '2012-10-17'

Version: '2012-10-17'

Statement:

Statement:

- Effect: Allow

- Effect: Allow

Principal:

Principal:

Service: lambda.amazonaws.com

Service: lambda.amazonaws.com

Action: sts:AssumeRole

Action: sts:AssumeRole

ManagedPolicyArns:

ManagedPolicyArns:

-

-

arn:aws:iam::aws:policy/service role/AWSLambdaBasicExecutionRole

arn:aws:iam::aws:policy/service role/AWSLambdaBasicExecutionRole

MyFunction:

MyFunction:

DependsOn: CopyZips

DependsOn: CopyZips

Type: AWS::Lambda::Function

Type: AWS::Lambda::Function

Properties:

Properties:

Description: Example

Description: Example

Handler: index.handler

Handler: index.handler

Runtime: nodejs12.x

Runtime: nodejs12.x

Role: !GetAtt 'MyFunctionRole.Arn'

Role: !GetAtt 'MyFunctionRole.Arn'

Timeout: 300

Timeout: 300

Code:

Code:

S3Bucket: !Ref 'LambdaZipsBucket'

S3Bucket: !Ref 'LambdaZipsBucket'

S3Key: !Sub '${QSS3KeyPrefix}/lambda.zi

S3Key: !Sub '${QSS3KeyPrefix}/lambda.zi

Once you’ve created the template file and modified it to reflect the resources above, you can deploy your functions from the command line with a single call:

创建模板文件并对其进行修改以反映上述资源后,您可以通过一次调用从命令行部署函数:

aws cloudformation deploy --template-file template.yml

aws cloudformation deploy --template-file template.yml

--stack-name your-stack-name-here

--stack-name your-stack-name-here

This basic configuration will allow you to deploy your functions once they‘ve been uploaded to the S3 bucket specified in the function definition. You can now build upon this basic set of deployment functionality to automate any aspect of your stack creation. For a fully functional deployment sample, you can clone the excellent quickstart repo from AWS.

通过基本配置,您可以在将函数上载到函数定义中指定的S3存储桶后对其进行部署。 现在,您可以基于这套基本的部署功能来自动化堆栈创建的任何方面。 对于功能齐全的部署示例,您可以从AWS克隆出色的快速入门仓库

一些技巧和其他资源 (Some Tips and Additional Resources)

As you work CloudFormation into your Lambda development pipeline, you’re bound to encounter headaches. Here are a few tips to help avoid unnecessary frustration from this immensely helpful AWS blog article on the topic:

在将CloudFormation应用于Lambda开发管道时,您肯定会遇到麻烦。 以下是一些技巧,可帮助您从有关该主题的非常有用的AWS博客文章中避免不必要的挫败感:

Did you know that you can deploy in-line Lambda code? Simply include your (small) Lambda function code as lines appended after the zipfile key.

您是否知道可以部署内联Lambda代码? 只需将您的(小的)Lambda函数代码包括在zipfile**之后的行中即可。

If you only need to release your functions to a small subset of AWS regions, you can provide a list of regional buckets to populate with your code; simply expand the resource listing when defining your source Lambda zip files.

如果您只需要将功能发布到一小部分AWS区域,则可以提供一个区域存储桶列表,以填充您的代码; 定义源Lambda zip文件时,只需扩展资源清单即可。

With a simple name format policy and some custom code, you can create a system that allows you to upload your S3 file once, then publish it to any AWS region that supports AWS Lambda.

使用简单的名称格式策略和一些自定义代码,您可以创建一个系统,该系统允许您一次上传S3文件,然后将其发布到支持AWS Lambda的任何AWS区域。

In addition to the AWS blog post above, my fellow IOD experts also had a few thoughts on the best ways to achieve serverless deployment zen:

除了上面的AWS博客文章之外,我的IOD专家还对实现无服务器部署zen的最佳方法有一些想法:

Mikhail Shilkov wrote an excellent summary of the path you can take to choose the best deployment tools for serverless applications. His thorough exploration of the topic is a powerful resource for guiding your decision process.

Mikhail Shilkov撰写了一篇精彩的总结,总结了 为无服务器应用程序选择最佳部署工具 的途径 他对该主题的深入探索是指导您决策过程的强大资源。

Slobodan Stojanovic gave a detailed overview of the path he took to simplifying his Lambda deployments; it serves as a good case study for transitioning your Lambda deployments into more maintainable patterns.

Slobodan Stojanovic详细介绍了他 简化Lambda部署所采用的方法 它是将Lambda部署转换为更可维护的模式的一个很好的案例研究。

Once again, the excellent Quickstart repo provided by AWS also offers a useful CloudFormation-driven tool for deploying your AWS Lambda code across multiple regions from a single bucket.

再次,AWS提供的出色的Quickstart存储库还提供了一个有用的CloudFormation驱动的工具,用于从一个存储桶跨多个区域部署您的AWS Lambda代码

摘要 (Summary)

AWS Lambda deployments are brittle and prone to error out-of-the-box, requiring you to wade through numerous user interfaces and dialog flows to create your function, associated execution roles, and the resources you need to host your deployable code.

AWS Lambda部署非常脆弱,易于出错,需要您耗费大量用户界面和对话流来创建函数,关联的执行角色以及托管可部署代码所需的资源。

With CloudFormation, you can convert all of this manual configuration into a single template file with the power to describe an entire application stack. CloudFormation replaces the complex and error-prone manual process of deploying Lambda functions with a repeatable, maintainable process that can be maintained alongside your code.

使用CloudFormation,您可以将所有手动配置转换为单个模板文件,并具有描述整个应用程序堆栈的功能。 CloudFormation用可重复且可维护的过程代替了部署Lambda函数的复杂且容易出错的手动过程,该过程可以与代码一起维护。

This expert writes regularly for the IOD blog, a weekly magazine of curated tech content geared toward developers. Check out more like this.

这位专家定期为IOD博客撰写文章,这是一本针对开发人员的精选技术内容的每周杂志。 像这样检查更多

翻译自: https://levelup.gitconnected.com/this-is-how-to-deploy-your-aws-lambda-functions-with-cloudformation-a21e7bbdb052