

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

AWS SAM 協助組織為其偏好的 CI/CD 系統建立管道，以便能夠以最少的努力實現 CI/CD 的優勢，例如加速部署頻率、縮短變更的前置時間，以及減少部署錯誤。

AWS SAM 透過建置容器映像的協助，簡化無伺服器應用程式的 CI/CD 任務。 AWS SAM 提供的映像包含 AWS SAM CLI多個支援 AWS Lambda 執行時間的 和 建置工具。這可讓您更輕鬆地使用 建置和封裝無伺服器應用程式 AWS SAM CLI。這些映像也減輕了團隊為 CI/CD 系統建立和管理自己映像的需求。如需 AWS SAM 建置容器映像的詳細資訊，請參閱[的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

多個 CI/CD 系統支援 AWS SAM 建置容器映像。您應該使用的 CI/CD 系統取決於幾個因素。這些包括您的應用程式是使用單一執行時間還是多個執行時間，還是您要在容器映像內或直接在主機上建置應用程式，可以是虛擬機器 (VM) 或裸機主機。

AWS SAM 也為封裝部署最佳實務 AWS的多個 CI/CD 系統提供一組預設管道範本。這些預設管道範本使用標準 JSON/YAML 管道組態格式，而內建的最佳實務有助於執行多帳戶和多區域部署，並確認管道無法對基礎設施進行意外變更。

您有兩個主要選項可使用 AWS SAM 來部署無伺服器應用程式：1) 修改現有管道組態以使用 AWS SAM CLI 命令，或 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)
+ [如何搭配 AWS SAM 管道使用 OIDC 身分驗證](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/)、[GitLab CI/CD](https://docs.gitlab.com/ee/ci/) 和 [GitHub 動作](https://github.com/features/actions)。

管道範本包含 AWS 部署最佳實務，可協助多帳戶和多區域部署。開發和生產等 AWS 環境通常存在於不同的 AWS 帳戶中。這可讓開發團隊設定安全的部署管道，而不會對基礎設施進行意外變更。

您也可以提供自己的自訂管道範本，以協助跨開發團隊標準化管道。

# 如何在部署時 AWS SAM 上傳本機檔案
<a name="deploy-upload-local-files"></a>

當您將應用程式部署到 時 AWS 雲端， AWS CloudFormation 需要先將本機檔案上傳到可存取 AWS 的服務，例如 Amazon Simple Storage Service (Amazon S3)。這包括 AWS SAM 範本參考的本機檔案。為了符合此需求，當您使用 `sam deploy`或 `sam package`命令時， 會 AWS SAM CLI執行下列動作：

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 範本中，我們使用 `CodeUri` 屬性參考 Lambda 函數程式碼的本機路徑。

```
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>

對於 AWS SAM CLI多種檔案類型、 CloudFormation 資源類型和 CloudFormation 巨集， 可以自動促進此程序。

### 檔案類型
<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`轉換的範例，請參閱 * Serverless Land* 的 [API Gateway HTTP API to 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 語法，並納入最佳實務，例如跨多個帳戶和區域管理成品，以及使用部署應用程式所需的最低許可量。目前，CLI AWS SAM 支援為 [AWS CodePipeline](https://aws.amazon.com/codepipeline)、[Jenkins](https://www.jenkins.io/)、[GitLab CI/CD、GitHub Actions 和 Bitbucket Pipelines 產生入門 CI/CD](https://docs.gitlab.com/ee/ci/) 管道組態。 [GitHub ](https://github.com/features/actions) [https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/)

以下是產生入門管道組態所需的高階任務：

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 中產生 的入門管道 AWS SAM](serverless-generating-example-ci-cd-codepipeline.md)。
+ 如果您使用的是 Jenkins、GitLab CI/CD、GitHub Actions 或 Bitbucket Pipelines，請參閱 [使用 AWS SAM 為 Jenkins、GitLab CI/CD、GitHub Actions、Bitbucket Pipelines 產生入門管道](serverless-generating-example-ci-cd-others.md)。

# 在 AWS CodePipeline 中產生 的入門管道 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>
```

如果您使用的是 GitHub 或 Bitbucket，則先前執行 **sam deploy**命令後，請依照*開發人員工具主控台使用者指南*中的更新待定連線主題中的**完成連線**步驟，完成連線。 [https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html)此外，請存放`CodeStarConnectionArn`來自 **sam deploy**命令輸出的 複本，因為如果您想要 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 研討會*中的[使用 CI/CD AWS CodePipeline](https://catalog.workshops.aws/complete-aws-sam/en-US/module-4-cicd)。

# 使用 AWS SAM 為 Jenkins、GitLab CI/CD、GitHub Actions、Bitbucket Pipelines 產生入門管道
<a name="serverless-generating-example-ci-cd-others"></a>

若要產生 Jenkins、GitLab CI/CD、GitHub Actions 或 Bitbucket Pipelines 的入門管道組態，請依此順序執行下列任務：

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 儲存庫的 GitLab CI/CD
具有 Bitbucket 儲存庫的 Bitbucket 管道

若要將 Git 儲存庫與您的 CI/CD 系統連線，請執行下列其中一項操作：
+ 如果您使用的是 Jenkins，請參閱「新增分支來源」的 [Jenkins 文件](https://www.jenkins.io/doc/book/pipeline/multibranch/)。
+ 如果您使用的是 GitLab CI/CD 和 GitLab 以外的 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](https://aws.amazon.com/blogs/compute/building-a-jenkins-pipeline-with-aws-sam/)一節中的指示****。下一個步驟需要 "Credential id"。
+ 如果您使用的是 GitLab CI/CD，請建立兩個「受保護的變數」，每個金鑰 ID 和私密金鑰各一個。遵循 [GitLab 文件](https://docs.gitlab.com/ee/ci/variables/)中的指示 – 在下一個步驟中，您將需要兩個「可變金鑰」。
+ 如果您使用的是 GitHub 動作，請建立兩個「加密的秘密」，每個金鑰和私密金鑰各一個。遵循 [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 研討會*中的[使用 CI/CDGitHub](https://s12d.com/sam-ws-en-gh)。

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

身為 CI/CD 管理員，您可能想要自訂入門管道範本和相關聯的引導式提示，組織中的開發人員可以使用這些提示來建立管道組態。

建立入門範本時， AWS SAM CLI會使用 Cookiecutter 範本。如需 Cookie 切線器範本的詳細資訊，請參閱 [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使用者提示回應映射至 Cookie 切換器範本的方式。若要查看此金鑰比對的範例，請參閱本主題稍後的 [範例檔案](#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 SAM CLI。

您現有 CI/CD 管道使用 部署無伺服器應用程式的程序 AWS SAM ，會因您使用的 CI/CD 系統而略有不同。

下列主題提供設定 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 Pipeline](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/) 以自動化 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 工作流程會使用一系列 GitHub 動作設定 Ubuntu 主機，然後執行 AWS SAM CLI命令來建置和部署 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)。

# 如何搭配 AWS SAM 管道使用 OIDC 身分驗證
<a name="deploying-with-oidc"></a>

AWS Serverless Application Model ()AWS SAM支援 Bitbucket、GitHub Actions 和 GitLab 持續整合和持續交付 (CI/CD) 平台的 OpenID Connect (OIDC) 使用者身分驗證。透過此支援，您可以使用任何這些平台的授權 CI/CD 使用者帳戶來管理您的無伺服器應用程式管道。否則，您將需要建立和管理多個 AWS Identity and Access Management (IAM) 使用者，以控制對 AWS SAM 管道的存取。

## 使用 AWS SAM 管道設定 OIDC
<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 《 使用者指南*》中的 [AWS::IAM::OIDCProvider](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>

以下是使用 AWS SAM 管道設定 OIDC 的範例。

```
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>

如需搭配 AWS SAM 管道使用 OIDC 的詳細資訊，請參閱 [sam pipeline bootstrap](sam-cli-command-reference-sam-pipeline-bootstrap.md)。