

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 CI/CD 系统和管道进行部署 AWS SAM
<a name="deploying-cicd-overview"></a>

AWS SAM 帮助组织为其首选 CI/CD 系统创建管道，以便他们可以毫不费力 CI/CD 地实现其中的好处，例如加快部署频率、缩短变更交付时间和减少部署错误。

AWS SAM 借助构建容器映像，简化无服务器应用程序的 CI/CD 任务。 AWS SAM 提供的映像包括许多受支持的 AWS Lambda 运行时的 AWS SAMCLI和构建工具。这使得使用构建和打包无服务器应用程序变得更加容易。 AWS SAMCLI这些映像还可以减轻团队为 CI/CD 系统创建和管理自己的映像的需求。有关 AWS SAM 构建容器镜像的更多信息，请参阅[的图像存储库 AWS SAM](serverless-image-repositories.md)。

多个 CI/CD 系统支持 AWS SAM 构建容器镜像。你应该使用哪种 CI/CD 系统取决于几个因素。这些因素包括：应用程序使用单个运行时系统还是多个运行时系统；您是要在容器映像中还是直接在主机（虚拟机 (VM) 或裸机主机）上构建应用程序。

AWS SAM 还为多个 CI/CD 系统提供了一组默认管道模板，这些模板封装 AWS了部署最佳实践。这些默认管道模板使用标准的 JSON/YAML 管道配置格式，内置的最佳实践有助于执行多账户和多区域部署，并验证管道不会对基础设施进行意外更改。

您可以使用两个主要选项 AWS SAM 来部署无服务器应用程序：1) 修改现有工作流配置以使用 AWS SAMCLI命令，或者 2) 生成一个示例工作 CI/CD 流配置，您可以将其用作自己应用程序的起点。

**Topics**
+ [什么是管线？](#deploying-whatis-pipeline)
+ [如何在 AWS SAM 部署时上传本地文件](deploy-upload-local-files.md)
+ [使用生成入门 CI/CD 管道 AWS SAM](serverless-generating-example-ci-cd.md)
+ [如何使用自定义入门管道 AWS SAM](serverless-customizing-starter-pipelines.md)
+ [自动部署您的 AWS SAM 应用程序](serverless-deploying-modify-pipeline.md)
+ [如何对管道使用 OIDC 身份验证 AWS SAM](deploying-with-oidc.md)

## 什么是管线？
<a name="deploying-whatis-pipeline"></a>

管线是一系列自动执行的步骤，用于发布应用程序的新版本。[借助 AWS SAM，您可以使用许多常用 CI/CD 系统来部署应用程序，包括 [AWS CodePipeline](https://aws.amazon.com/codepipeline)[Jenkins](https://www.jenkins.io/)、C [GitLab I/CD 和 Ac](https://docs.gitlab.com/ee/ci/) tions。GitHub](https://github.com/features/actions)

管道模板包括 AWS 部署最佳实践，可帮助进行多账户和多区域部署。 AWS 诸如开发和生产环境之类的环境通常存在于不同的 AWS 账户中。这允许开发团队配置安全的部署管线，而无需对基础设施进行意外更改。

您还可以提供自己的自定义管线模板，以帮助跨开发团队标准化管线。

# 如何在 AWS SAM 部署时上传本地文件
<a name="deploy-upload-local-files"></a>

当您将应用程序部署到时 AWS 云， AWS CloudFormation 需要先将本地文件上传到可访问的 AWS 服务，例如亚马逊简单存储服务 (Amazon S3) Service。这包括您的 AWS SAM 模板引用的本地文件。为了满足此要求，在使用 `sam deploy` 或 `sam package` 命令时， AWS SAMCLI 会执行以下操作：

1. 自动将您的本地文件上传到可访问的 AWS 服务。

1. 自动更新应用程序模板以引用新的文件路径。

**Topics**
+ [演示：使用 AWS SAM CLI 上传 Lambda 函数代码](#deploy-upload-local-files-demo)
+ [支持的使用案例](#deploy-upload-local-files-use)
+ [了解详情](#deploy-upload-local-files-learn)

## 演示：使用 AWS SAM CLI 上传 Lambda 函数代码
<a name="deploy-upload-local-files-demo"></a>

在这个演示中，我们使用 Lambda 函数的 .zip 包类型初始化示例 Hello World 应用程序。我们使用 AWS SAM CLI 自动将 Lambda 函数代码上传到 Amazon S3，并在应用程序模板中引用其新路径。

首先，我们运行 `sam init` 以初始化 Hello World 应用程序。

```
$ sam init
...
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        ...
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: y

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: demo

    -----------------------
    Generating application:
    -----------------------
    Name: demo
    Runtime: python3.9
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    Configuration file: demo/samconfig.toml
    
...
```

我们的 Lambda 函数代码组织在项目的 `hello_world` 子目录中。

```
demo
├── README.md
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── template.yaml
└── tests
```

在 AWS SAM 模板中，我们使用属性引用 Lambda 函数代码的本地路径。`CodeUri`

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      ...
```

接下来，运行 `sam build` 以构建应用程序并准备部署。

```
$ sam build
Starting Build use cache
Manifest file is changed (new hash: 3298f13049d19cffaa37ca931dd4d421) or dependency folder (.aws-sam/deps/7896875f-9bcc-4350-8adb-2c1d543627a1) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
Building codeuri: /Users/.../demo/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CleanUp
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml
...
```

然后，运行 `sam deploy --guided` 部署应用程序。

```
$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [demo]: ENTER
        AWS Region [us-west-2]: ENTER
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: n
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: ENTER
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: ENTER
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: ENTER
        SAM configuration file [samconfig.toml]: ENTER
        SAM configuration environment [default]: ENTER

        Looking for resources needed for deployment:
        ...
        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at 
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

File with same data already exists at demo/da3c598813f1c2151579b73ad788cac8, skipping upload

        Deploying with following values
        ===============================
        Stack name                   : demo
        Region                       : us-west-2
        Confirm changeset            : False
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
...
Waiting for changeset to be created..
CloudFormation stack changeset
-------------------------------------------------------------------------------------------------
Operation                LogicalResourceId        ResourceType             Replacement            
-------------------------------------------------------------------------------------------------
+ Add                    HelloWorldFunctionHell   AWS::Lambda::Permissio   N/A                    
                         oWorldPermissionProd     n                                               
+ Add                    HelloWorldFunctionRole   AWS::IAM::Role           N/A                    
...                     
-------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680906292/1164338d-72e7-4593-a372-f2b3e67f542f

2023-04-07 12:24:58 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------
ResourceStatus           ResourceType             LogicalResourceId        ResourceStatusReason   
-------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   Resource creation      
                                                                           Initiated              
...                    
-------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
-------------------------------------------------------------------------------------------------
Outputs                                                                                         
-------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                   
Description         Implicit IAM Role created for Hello World function                          
Value               arn:aws:iam::012345678910:role/demo-HelloWorldFunctionRole-VQ4CU7UY7S2K     

Key                 HelloWorldApi                                                               
Description         API Gateway endpoint URL for Prod stage for Hello World function            
Value               https://satnon55e9.execute-api.us-west-2.amazonaws.com/Prod/hello/          

Key                 HelloWorldFunction                                                          
Description         Hello World Lambda Function ARN                                             
Value               arn:aws:lambda:us-west-2:012345678910:function:demo-                        
HelloWorldFunction-G14inKTmSQvK                                                                 
-------------------------------------------------------------------------------------------------
Successfully created/updated stack - demo in us-west-2
```

在部署期间， AWS SAM CLI 会自动将我们的 Lambda 函数代码上传到 Amazon S3 并更新模板。我们在 CloudFormation 控制台中修改后的模板反映了 Amazon S3 存储桶路径。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: s3://aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr/demo/da3c598813f1c2151579b73ad788cac8
      Handler: app.lambda_handler
      ...
```

## 支持的使用案例
<a name="deploy-upload-local-files-use"></a>

对于多种文件类型、 CloudFormation 资源类型和 CloudFormation 宏， AWS SAMCLI可以自动简化此过程。

### 文件类型
<a name="deploy-upload-local-files-use-types"></a>

支持应用程序文件和 Docker 映像。

### CloudFormation 资源类型
<a name="deploy-upload-local-files-use-resources"></a>

以下是支持的资源类型及其属性的列表：


| 资源 | Properties | 
| --- | --- | 
| AWS::ApiGateway::RestApi | BodyS3Location | 
| AWS::ApiGatewayV2::Api | BodyS3Location | 
| AWS::AppSync:FunctionConfiguration |  `CodeS3Location` `RequestMappingTemplateS3Location` `ResponseMappingTemplateS3Location`  | 
| AWS::AppSync::GraphQLSchema | DefinitionS3Location | 
| AWS::AppSync::Resolver |  `CodeS3Location` `RequestMappingTemplateS3Location` `ResponseMappingTemplateS3Location`  | 
| AWS::CloudFormation::ModuleVersion | ModulePackage | 
| AWS::CloudFormation::ResourceVersion | SchemaHandlerPackage | 
| AWS::ECR::Repository | RepositoryName | 
| AWS::ElasticBeanstalk::ApplicationVersion | SourceBundle | 
| AWS::Glue::Job | Command.ScriptLocation | 
| AWS::Lambda::Function |  `Code` `Code.ImageUri`  | 
| AWS::Lambda::LayerVersion | Content | 
| AWS::Serverless::Api | DefinitionUri | 
| AWS::Serverless::Function |  `CodeUri` `ImageUri`  | 
| AWS::Serverless::GraphQLApi |  `SchemaUri` `Function.CodeUri` `Resolver.CodeUri`  | 
| AWS::Serverless::HttpApi | DefinitionUri | 
| AWS::Serverless::LayerVersion | ContentUri | 
| AWS::Serverless::StateMachine | DefinitionUri | 
| AWS::StepFunctions::StateMachine | DefinitionS3Location | 

### CloudFormation 宏
<a name="deploy-upload-local-files-use-macros"></a>

支持使用 `AWS::Include` 转换宏引用的文件。

## 了解详情
<a name="deploy-upload-local-files-learn"></a>

要了解有关`AWS::Include`变换的更多信息，请参阅《*AWS CloudFormation 用户指南*》中的[ AWS::Include 变换](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html)。

要查看在 AWS SAM 模板中使用`AWS::Include`转换的示例，请参阅 S *erver* less Land 上[的 API Gateway HTTP API 到 SQS](https://serverlessland.com/patterns/apigw-sqs) 模式。

# 使用生成入门 CI/CD 管道 AWS SAM
<a name="serverless-generating-example-ci-cd"></a>

准备好自动部署后，您可以使用其中 AWS SAM一个入门级管道模板为您选择使用的 CI/CD 系统生成部署管道。您的部署管线是您配置并用于自动部署无服务器应用程序的工具。入门管线模板已预配置，可帮助您快速为无服务器应用程序设置部署管线。

借助入门管线模板，您可以使用 [sam pipeline init](sam-cli-command-reference-sam-pipeline-init.md) 命令在几分钟内生成管线。

入门级管道模板使用熟悉的 CI/CD 系统 JSON/YAML 语法，并纳入了最佳实践，例如跨多个账户和区域管理工件，以及使用部署应用程序所需的最低权限量。[https://github.com/features/actions](https://github.com/features/actions)

以下是生成入门管道配置所需执行的高级任务：

1. **创建基础设施资源** — 您的管道需要某些 AWS 资源，例如具有必要权限的 IAM 用户和角色、Amazon S3 存储桶，以及可选的 Amazon ECR 存储库。

1. 将 **Git 仓库与 CI/CD 系统连接起来** — 您的 CI/CD 系统需要知道哪个 Git 仓库会触发管道的运行。请注意，此步骤可能不是必需的，具体取决于您使用的 Git 存储库和 CI/CD 系统的组合。

1. **生成管道配置** – 此步骤将生成包括两个部署阶段的入门管道配置。

1. 将@@ **您的工作流配置提交到 Git 存储库** — 此步骤对于确保您的 CI/CD 系统知道您的工作流配置是必要的，并且将在提交更改时运行。

生成入门管道配置并将其提交到 Git 存储库后，每当有人向该存储库提交代码更改时，您的管道就会被触发自动运行。

这些步骤的顺序和每个步骤的详细信息因您的 CI/CD 系统而异：
+ 如果您正在使用 AWS CodePipeline，请参阅[正在为 AWS CodePipeline in 生成入门管道 AWS SAM](serverless-generating-example-ci-cd-codepipeline.md)。
+ 如果你使用的是 Jenkins、C GitLab I/CD、Actions 或 Bitbucket Pipelines，请参 GitHub 阅。[用于 AWS SAM 为 Jenkins、C GitLab I/CD、Actions、Bitbucket Pipelines 生成入 GitHub](serverless-generating-example-ci-cd-others.md)

# 正在为 AWS CodePipeline in 生成入门管道 AWS SAM
<a name="serverless-generating-example-ci-cd-codepipeline"></a>

要为生成入门工作流配置 AWS CodePipeline，请按以下顺序执行以下任务：

1. 创建基础设施资源

1. 生成管道配置

1. 将管道配置提交到 Git

1. 将你的 Git 仓库与你的 CI/CD 系统连接起来

**注意**  
以下过程使用两个 AWS SAM CLI 命令：`sam pipeline bootstrap` 和 `sam pipeline init`。之所以有两个命令，是为了处理这样的用例：管理员（即需要设置基础设施 AWS 资源的权限的用户，比如 IAM 用户和角色）比开发人员（即只需要设置单个管道的权限，而不需要所需的基础设施 AWS 资源的用户）拥有更多的权限。

## 第 1 步：创建基础设施资源
<a name="generating-example-step-1"></a>

使用的管道 AWS SAM 需要某些 AWS 资源，例如具有必要权限的 IAM 用户和角色、Amazon S3 存储桶，以及可选的 Amazon ECR 存储库。对于管道的每个部署阶段，您都必须拥有一组基础设施资源。

您可以运行以下命令来帮助完成此设置：

```
sam pipeline bootstrap
```

**注意**  
为管道的每个部署阶段运行上一条命令。

## 第 2 步：生成管道配置
<a name="generating-example-step-2"></a>

要生成管道配置，请运行以下命令：

```
sam pipeline init
```

## 第 3 步：将管道配置提交到 Git 存储库
<a name="generating-example-step-3"></a>

此步骤对于确保您的 CI/CD 系统知道您的工作流配置是必要的，并且将在提交更改时运行。

## 第 4 步：将 Git 存储库与 CI/CD 系统连接
<a name="generating-example-step-4"></a>

因为 AWS CodePipeline 您现在可以通过运行以下命令来创建连接：

```
sam deploy -t codepipeline.yaml --stack-name <pipeline-stack-name> --capabilities=CAPABILITY_IAM --region <region-X>
```

如果您使用的是 Bitbucket， GitHub 则在之前运行**sam deploy**命令后，请按照*开发者工具控制台用户指南*中 “[更新待处理的**连接” 主题中的 “完成**连接](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html)” 下的步骤完成连接，完成连接。此外，请存储**sam deploy**命令输出`CodeStarConnectionArn`中的副本，因为如果您想与之以外的其他分支 AWS CodePipeline 一起使用，则需要该副本`main`。

## 配置其他分支
<a name="configuring-other-branches"></a>

默认情况下， AWS CodePipeline 使用带的`main`分支 AWS SAM。如果要使用 `main` 以外的分支，则必须再次运行 **sam deploy** 命令。请注意，根据使用的 Git 仓库，还可能需要提供 `CodeStarConnectionArn`：

```
# For GitHub and Bitbucket
sam deploy -t codepipeline.yaml --stack-name <feature-pipeline-stack-name> --capabilities=CAPABILITY_IAM --parameter-overrides="FeatureGitBranch=<branch-name> CodeStarConnectionArn=<codestar-connection-arn>"

# For AWS CodeCommit
sam deploy -t codepipeline.yaml --stack-name <feature-pipeline-stack-name> --capabilities=CAPABILITY_IAM --parameter-overrides="FeatureGitBranch=<branch-name>"
```

## 了解详情
<a name="serverless-generating-cicd-learn"></a>

有关设置 CI/CD 管道的动手示例，请参阅*完整 AWS SAM *研讨会 AWS CodePipeline中的 [CI/CD](https://catalog.workshops.aws/complete-aws-sam/en-US/module-4-cicd)。

# 用于 AWS SAM 为 Jenkins、C GitLab I/CD、Actions、Bitbucket Pipelines 生成入 GitHub
<a name="serverless-generating-example-ci-cd-others"></a>

要为 Jenkins、C GitLab I/CD、Actions 或 Bitbucket Pipelines 生成入门工作流配置，请按以下顺序执行以下任务： GitHub 

1. 创建基础设施资源

1. 将你的 Git 仓库与你的 CI/CD 系统连接起来

1. 创建凭证对象

1. 生成管道配置

1. 将管道配置提交到 Git 存储库

**注意**  
以下过程使用两个 AWS SAM CLI 命令：`sam pipeline bootstrap` 和 `sam pipeline init`。之所以有两个命令，是为了处理这样的用例：管理员（即需要设置基础设施 AWS 资源的权限的用户，比如 IAM 用户和角色）比开发人员（即只需要设置单个管道的权限，而不需要所需的基础设施 AWS 资源的用户）拥有更多的权限。

## 第 1 步：创建基础设施资源
<a name="generating-example-step-1"></a>

使用的管道 AWS SAM 需要某些 AWS 资源，例如具有必要权限的 IAM 用户和角色、Amazon S3 存储桶，以及可选的 Amazon ECR 存储库。对于管道的每个部署阶段，您都必须拥有一组基础设施资源。

您可以运行以下命令来帮助完成此设置：

```
sam pipeline bootstrap
```

**注意**  
为管道的每个部署阶段运行上一条命令。

您必须为管道的每个部署阶段捕获管道用户的 AWS 证书（密钥 ID 和私有密钥），因为后续步骤需要这些证书。

## 第 2 步：将 Git 存储库与 CI/CD 系统连接
<a name="generating-example-step-2"></a>

必须将 Git 存储库连接到 CI/CD 系统，这样 CI/CD 系统才能访问用于构建和部署的应用程序源代码。

**注意**  
如果您使用以下组合之一，则可以跳过此步骤，因为连接会自动完成：  
GitHub 使用 GitHub 存储库执行的操作
GitLab 带有存储库的 CI/CD GitLab 
带有 Bitbucket 存储库的 Bitbucket 管线

要将 Git 存储库与 CI/CD 系统连接，请执行以下任一操作：
+ 如果您使用的是 Jenkins，请参阅 [Jenkins 文档](https://www.jenkins.io/doc/book/pipeline/multibranch/)中的“添加分支源”。
+ 如果您使用的是 C GitLab I/CD 和除之外的 Git 存储库 GitLab，请参阅 “连接外部存储库” [GitLab文档](https://docs.gitlab.com/ee/ci/ci_cd_for_external_repos/)。

## 第 3 步：创建凭证对象
<a name="generating-example-step-3"></a>

每个 CI/CD 系统都有自己的方式来管理 CI/CD 系统访问您的 Git 存储库所需的凭据。

要创建必需的凭证对象，请执行以下操作之一：
+ 如果您使用的是 Jenkins，请创建一个存储密钥 ID 和密钥的“凭证”。请按照**配置 Jenkins** 部分里[使用 AWS SAM构建 Jenkins 管道](https://aws.amazon.com/blogs/compute/building-a-jenkins-pipeline-with-aws-sam/)博客中的说明进行操作。下一步您将需要用到“凭证 ID”。
+ 如果您使用的是 C GitLab I/CD，请创建两个 “受保护变量”，密钥 ID 和密钥各一个。按照[GitLab 文档](https://docs.gitlab.com/ee/ci/variables/)中的说明进行操作 — 下一步需要两个 “变量键”。
+ 如果您使用的是 Ac GitHub tions，请创建两个 “加密机密”，密钥和密钥各一个。按照[GitHub文档](https://docs.github.com/en/actions/reference/encrypted-secrets)中的说明进行操作——下一步需要两个 “机密名称”。
+ 如果您使用的是 Bitbucket 管线，请创建两个“安全变量”，密钥 ID 和密钥各一个。请按照[变量和密钥](https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets)中的说明进行操作。下一步您将需要两个“密钥名称”。

## 第 4 步：生成管道配置
<a name="generating-example-step-4"></a>

要生成管道配置，请运行以下命令。您需要输入在上一步中创建的凭证对象：

```
sam pipeline init
```

## 第 5 步：将管道配置提交到 Git 存储库
<a name="generating-example-step-5"></a>

此步骤对于确保您的 CI/CD 系统知道您的工作流配置是必要的，并且将在提交更改时运行。

## 了解详情
<a name="serverless-generating-other-cicd-learn"></a>

有关使用设置 CI/CD 管道的动手示例GitHub Actions，请参阅*完整 AWS SAM *研讨会GitHub中的 [CI/CD](https://s12d.com/sam-ws-en-gh)。

# 如何使用自定义入门管道 AWS SAM
<a name="serverless-customizing-starter-pipelines"></a>

作为 CI/CD 管理员，您可能需要自定义入门工作流模板和相关的指导性提示，组织中的开发人员可以使用这些模板来创建工作流配置。

在创建入门模板时 AWS SAM CLI 使用 Cookiecutter 模板。有关 cookiecutter 模板的详细信息，请访问 [Cookiecutter](https://cookiecutter.readthedocs.io/en/latest/README.html)。

您还可以自定义使用 `sam pipeline init` 命令创建管道配置时 AWS SAM CLI 向用户显示的提示。要自定义用户提示，请执行以下操作：

1. **创建 `questions.json` 文件** – 该 `questions.json` 文件必须位于项目存储库的根目录中。这是与 `cookiecutter.json` 文件相同的目录。要查看 `questions.json` 文件的架构，请参阅 [questions.json.schema](https://github.com/aws/aws-sam-cli/blob/2b831b29f76ac9c4e0cbcbd68b37f8f664e136d8/samcli/lib/pipeline/init/questions.json.schema)。要查看示例 `questions.json` 文件，请参阅 [questions.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/questions.json)。

1. **使用 cookiecutter 名称映射问题键** – `questions.json` 文件中的每个对象都需要一个与 cookiecutter 模板中的名称相匹配的键。这种键匹配即 AWS SAM CLI 如何将用户提示响应映射到 cookiecutter 模板。要查看此键匹配示例，请参阅本主题后面的 [示例文件](#serverless-customizing-starter-pipelines-example-files) 部分。

1. **创建 `metadata.json` 文件** – 在 `metadata.json` 文件中声明管道将包含的阶段数。阶段数指示 `sam pipeline init` 命令提示多少阶段的信息，或者如果是 `--bootstrap` 选项，则为多少阶段创建基础架构资源。要查看声明具有两个阶段的管道的示例 `metadata.json` 文件，请参阅 [metadata.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/metadata.json)。

## 示例项目
<a name="serverless-customizing-starter-pipelines-example-projects"></a>

以下是示例项目，每个项目都包含一个 Cookiecutter 模板、一个 `questions.json` 文件和一个 `metadata.json` 文件：
+ Jenkins 示例：[两阶段 Jenkins 管道模板](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/Jenkins/two-stage-pipeline-template)
+ CodePipeline 示例：[两阶段 CodePipeline 管道模板](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/AWS-CodePipeline/two-stage-pipeline-template)

## 示例文件
<a name="serverless-customizing-starter-pipelines-example-files"></a>

以下一组文件显示了 `questions.json` 文件中的问题如何与 Cookiecutter 模板文件中的条目相关联。请注意，这些示例是文件片段，并非完整文件。要查看完整文件的示例，请参阅本主题前面的 [示例项目](#serverless-customizing-starter-pipelines-example-projects) 部分。

示例 **`questions.json`**：

```
{
  "questions": [{
    "key": "intro",
    "question": "\nThis template configures a pipeline that deploys a serverless application to a testing and a production stage.\n",
    "kind": "info"
  }, {
    "key": "pipeline_user_jenkins_credential_id",
    "question": "What is the Jenkins credential ID (via Jenkins plugin \"aws-credentials\") for pipeline user access key?",
    "isRequired": true
  }, {
    "key": "sam_template",
    "question": "What is the template file path?",
    "default": "template.yaml"
  }, {
    ...
```

示例 **`cookiecutter.json`**：

```
{
  "outputDir": "aws-sam-pipeline",
  "pipeline_user_jenkins_credential_id": "",
  "sam_template": "",
    ...
```

示例 **`Jenkinsfile`**：

```
pipeline {
  agent any
  environment {
    PIPELINE_USER_CREDENTIAL_ID = '{{cookiecutter.pipeline_user_jenkins_credential_id}}'
    SAM_TEMPLATE = '{{cookiecutter.sam_template}}'
    ...
```

# 自动部署您的 AWS SAM 应用程序
<a name="serverless-deploying-modify-pipeline"></a>

在中 AWS SAM，自动部署 AWS SAM 应用程序的方式因所使用的 CI/CD 系统而异。因此，本节中的示例向您展示了如何配置各种 CI/CD 系统，以便在 AWS SAM 构建容器映像中自动构建无服务器应用程序。这些构建容器镜像可以更轻松地使用构建和打包无服务器应用程序。 AWS SAMCLI

根据您使用的 CI/CD 系统，现有 CI/CD 管道部署无服务器应用程序的过程略 AWS SAM 有不同。

以下主题提供了配置 CI/CD 系统以在构建容器映像中构建无服务器应用程序的 AWS SAM 示例：

**Topics**
+ [使用与 AWS CodePipeline 进行部署 AWS SAM](deploying-using-codepipeline.md)
+ [使用 Bitbucket 流水线进行部署 AWS SAM](deploying-using-bitbucket.md)
+ [使用 Jenkins 进行部署 AWS SAM](deploying-using-jenkins.md)
+ [使用 GitLab CI/CD 进行部署 AWS SAM](deploying-using-gitlab.md)
+ [使用 GitHub 操作进行部署 AWS SAM](deploying-using-github.md)

# 使用与 AWS CodePipeline 进行部署 AWS SAM
<a name="deploying-using-codepipeline"></a>

要将[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)管道配置为自动生成和部署 AWS SAM 应用程序，您的 CloudFormation 模板和`buildspec.yml`文件必须包含执行以下操作的行：

1. 从可用映像中引用具有必要运行时的构建容器映像。以下示例使用 `public.ecr.aws/sam/build-nodejs20.x` 构建容器映像。

1. 配置管道阶段以运行必要的 AWS SAM 命令行界面 (CLI) 命令。以下示例运行两个 AWS SAM CLI 命令：**sam build** 和 **sam deploy**（带有必要的选项）。

此示例假设您已使用声明 AWS SAM 模板文件中的所有函数和层`runtime: nodejs20.x`。

**CloudFormation 模板片段：**

```
  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: public.ecr.aws/sam/build-nodejs20.x
        Type: LINUX_CONTAINER
      ...
```

**`buildspec.yml` 片段：**

```
version: 0.2
phases:
  build:
    commands:
      - sam build
      - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

有关不同运行时的可用 Amazon Elastic Container Registry (Amazon ECR) 构建容器映像的列表，请参阅 [的图像存储库 AWS SAM](serverless-image-repositories.md)。

# 使用 Bitbucket 流水线进行部署 AWS SAM
<a name="deploying-using-bitbucket"></a>

要将 [Bitbucket Pipelin](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/) e 配置为自动构建和部署 AWS SAM 应用程序，您的`bitbucket-pipelines.yml`文件必须包含执行以下操作的行：

1. 从可用映像中引用具有必要运行时的构建容器映像。以下示例使用 `public.ecr.aws/sam/build-nodejs20.x` 构建容器映像。

1. 配置管道阶段以运行必要的 AWS SAM 命令行界面 (CLI) 命令。以下示例运行两个 AWS SAM CLI 命令：**sam build** 和 **sam deploy**（带有必要的选项）。

此示例假设您已使用声明 AWS SAM 模板文件中的所有函数和层`runtime: nodejs20.x`。

```
image: public.ecr.aws/sam/build-nodejs20.x

pipelines:
  branches:
    main: # branch name
      - step:
          name: Build and Package
          script:
            - sam build
            - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

有关不同运行时的可用 Amazon Elastic Container Registry (Amazon ECR) 构建容器映像的列表，请参阅 [的图像存储库 AWS SAM](serverless-image-repositories.md)。

# 使用 Jenkins 进行部署 AWS SAM
<a name="deploying-using-jenkins"></a>

要将 [Jenkins](https://www.jenkins.io/) 管道配置为自动生成和部署 AWS SAM 应用程序，`Jenkinsfile`必须包含执行以下操作的行：

1. 从可用映像中引用具有必要运行时的构建容器映像。以下示例使用 `public.ecr.aws/sam/build-nodejs20.x` 构建容器映像。

1. 配置管道阶段以运行必要的 AWS SAM 命令行界面 (CLI) 命令。以下示例运行两个 AWS SAM CLI 命令：**sam build** 和 **sam deploy**（带有必要的选项）。

此示例假设您已使用声明 AWS SAM 模板文件中的所有函数和层`runtime: nodejs20.x`。

```
pipeline {
    agent { docker { image 'public.ecr.aws/sam/build-nodejs20.x' } }
    stages {
        stage('build') {
            steps {
                sh 'sam build'
                sh 'sam deploy --no-confirm-changeset --no-fail-on-empty-changeset'
            }
        }
    }
}
```

有关不同运行时的可用 Amazon Elastic Container Registry (Amazon ECR) 构建容器映像的列表，请参阅 [的图像存储库 AWS SAM](serverless-image-repositories.md)。

# 使用 GitLab CI/CD 进行部署 AWS SAM
<a name="deploying-using-gitlab"></a>

要将[GitLab](https://about.gitlab.com)管道配置为自动生成和部署 AWS SAM 应用程序，您的`gitlab-ci.yml`文件必须包含执行以下操作的行：

1. 从可用映像中引用具有必要运行时的构建容器映像。以下示例使用 `public.ecr.aws/sam/build-nodejs20.x` 构建容器映像。

1. 配置管道阶段以运行必要的 AWS SAM 命令行界面 (CLI) 命令。以下示例运行两个 AWS SAM CLI 命令：**sam build** 和 **sam deploy**（带有必要的选项）。

此示例假设您已使用声明 AWS SAM 模板文件中的所有函数和层`runtime: nodejs20.x`。

```
image: public.ecr.aws/sam/build-nodejs20.x
deploy:
  script:
    - sam build
    - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

有关不同运行时的可用 Amazon Elastic Container Registry (Amazon ECR) 构建容器映像的列表，请参阅 [的图像存储库 AWS SAM](serverless-image-repositories.md)。

# 使用 GitHub 操作进行部署 AWS SAM
<a name="deploying-using-github"></a>

要将[GitHub](https://github.com/)管道配置为自动生成和部署 AWS SAM 应用程序，必须先在主机上安装 AWS SAM 命令行界面 (CLI)。您可以在 GitHub 工作流程中使用[GitHub 操作](https://github.com/features/actions)来帮助完成此设置。

以下示例 GitHub 工作流程使用一系列 GitHub操作设置 Ubuntu 主机，然后运行 AWS SAMCLI命令来构建和部署应用程序： AWS SAM 

```
on:
  push:
    branches:
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v3
      - uses: aws-actions/setup-sam@v2
      - uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-2
      - run: sam build --use-container
      - run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

有关不同运行时的可用 Amazon Elastic Container Registry (Amazon ECR) 构建容器映像的列表，请参阅 [的图像存储库 AWS SAM](serverless-image-repositories.md)。

# 如何对管道使用 OIDC 身份验证 AWS SAM
<a name="deploying-with-oidc"></a>

AWS Serverless Application Model (AWS SAM) 支持 OpenID Connect (OIDC) 用户身份验证，支持 Bitbucket、 GitHub Actions、 GitLab 持续集成和持续交付（来自这些平台的CI/CD) platforms. With this support, you can use authorized CI/CD用户账户），用于管理您的无服务器应用程序管道。 否则，您需要创建和管理多个 AWS Identity and Access Management (IAM) 用户来控制对 AWS SAM 管道的访问权限。

## 使用管道设置 OIDC AWS SAM
<a name="deploying-with-oidc-setup"></a>

在`sam pipeline bootstrap`配置过程中，请执行以下操作以在您的 AWS SAM 管道中设置 OIDC。

1. 当系统提示您选择身份提供商时，请选择 **OIDC**。

1. 接下来，选择支持的 OIDC 提供商。

1. 输入 OIDC 提供商 URL，以 **https://** 开头。
**注意**  
AWS SAM 生成`AWS::IAM::OIDCProvider`资源类型时会引用此 URL。

1. 接下来，按照提示输入访问所选 CI/CD 平台所需的平台信息。这些详细信息因平台而异，可能包括：
   + OIDC 客户端 ID。
   + 代码存储库名称或通用唯一标识符 (UUID)。
   + 与存储库关联的组或组织名称。
   + GitHub 代码仓库所属的组织。
   + GitHub 存储库名称。
   + 部署将发生的分支。

1. AWS SAM 显示输入的 OIDC 配置的摘要。输入某项设置的数字进行编辑，或按下 Enter 以继续。

1. 当系统提示您确认创建支持输入的 OIDC 连接所需的资源时，按下 Y 以继续。

AWS SAM 使用提供的配置生成一个承担管道执行角色的`AWS::IAM::OIDCProvider` AWS CloudFormation 资源。要了解有关此 CloudFormation 资源类型的更多信息，请参阅*AWS CloudFormation 用户指南OIDCProvider*中的 [AWS:: IAM](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-oidcprovider.html)::。

**注意**  
如果身份提供者 (IdP) 资源已存在于您的中 AWS 账户，请 AWS SAM 引用该资源，而不是创建新资源。

## 示例
<a name="deploying-with-oidc-setup-example"></a>

以下是使用管道设置 OIDC 的 AWS SAM 示例。

```
Select a permissions provider:
    1 - IAM (default)
    2 - OpenID Connect (OIDC)
Choice (1, 2): 2
Select an OIDC provider:
    1 - GitHub Actions
    2 - GitLab
    3 - Bitbucket
Choice (1, 2, 3): 1
Enter the URL of the OIDC provider [https://token.actions.githubusercontent.com]:
Enter the OIDC client ID (sometimes called audience) [sts.amazonaws.com]:
Enter the GitHub organization that the code repository belongs to. If there is no organization enter your username instead: my-org
Enter GitHub repository name: testing
Enter the name of the branch that deployments will occur from [main]:

[3] Reference application build resources
Enter the pipeline execution role ARN if you have previously created one, or we will create one for you []:
Enter the CloudFormation execution role ARN if you have previously created one, or we will create one for you []:
Please enter the artifact bucket ARN for your Lambda function. If you do not have a bucket, we will create one for you []:
Does your application contain any IMAGE type Lambda functions? [y/N]:

[4] Summary
Below is the summary of the answers:
    1 - Account: 123456
    2 - Stage configuration name: dev
    3 - Region: us-east-1
    4 - OIDC identity provider URL: https://token.actions.githubusercontent.com
    5 - OIDC client ID: sts.amazonaws.com
    6 - GitHub organization: my-org
    7 - GitHub repository: testing
    8 - Deployment branch: main
    9 - Pipeline execution role: [to be created]
    10 - CloudFormation execution role: [to be created]
    11 - Artifacts bucket: [to be created]
    12 - ECR image repository: [skipped]
Press enter to confirm the values above, or select an item to edit the value:

This will create the following required resources for the 'dev' configuration:
    - IAM OIDC Identity Provider
    - Pipeline execution role
    - CloudFormation execution role
    - Artifact bucket
Should we proceed with the creation? [y/N]:
```

## 了解详情
<a name="deploying-with-oidc-setup-learn-more"></a>

有关将 OIDC 与 AWS SAM 管道配合使用的更多信息，请参阅。[sam pipeline bootstrap](sam-cli-command-reference-sam-pipeline-bootstrap.md)