

# Deploy your application and resources with AWS SAM
<a name="serverless-deploying"></a>

Deploying your application provisions and configures your AWS resources in the AWS Cloud, making your application run in the cloud. AWS SAM uses [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) as its underlying deployment mechanism. AWS SAM uses the build artifacts you create when running the **sam build** command as the standard inputs for deploying your serverless application.

With AWS SAM, you can deploy your serverless application manually, or you can automate deployments. To automate deployments, you use AWS SAM pipelines with a continuous integration and continuous deployment (CI/CD) system of your choice. Your deployment pipeline is an automated sequence of steps that are performed to release a new version of your serverless application. 

The topics in this section provide guidance on both automated and manual deployments. To deploy your application manually, you use AWS SAM CLI commands. To automate deployments, refer to the topics in this section. They specifically provide in-depth content on automating deployments using pipelines and a CI/CD system. This includes generating a starter pipeline, setting up automation, troubleshooting deployments, using OpenID Connect (OIDC) user authentication, and uploading local files at deployment.

**Topics**
+ [

# Introduction to deploying with AWS SAM
](using-sam-cli-deploy.md)
+ [

# Options for deploying your application with AWS SAM
](deploying-options.md)
+ [

# Using CI/CD systems and pipelines to deploy with AWS SAM
](deploying-cicd-overview.md)
+ [

# Introduction to using sam sync to sync to AWS Cloud
](using-sam-cli-sync.md)

# Introduction to deploying with AWS SAM
<a name="using-sam-cli-deploy"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam deploy` command to deploy your serverless application to the AWS Cloud.
+ For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli).
+ For a list of `sam deploy` command options, see [sam deploy](sam-cli-command-reference-sam-deploy.md).
+ For an example of using `sam deploy` during a typical development workflow, see [Step 3: Deploy your application to the AWS Cloud](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-deploy).

**Topics**
+ [

## Prerequisites
](#using-sam-cli-deploy-prerequisites)
+ [

## Deploying applications using sam deploy
](#using-sam-cli-deploy-deploying)
+ [

## Best practices
](#using-sam-cli-deploy-best)
+ [

## Options for sam deploy
](#using-sam-cli-deploy-options)
+ [

## Troubleshooting
](#using-sam-cli-deploy-troubleshooting)
+ [

## Examples
](#using-sam-cli-deploy-examples)
+ [

## Learn more
](#using-sam-cli-deploy-learn)

## Prerequisites
<a name="using-sam-cli-deploy-prerequisites"></a>

To use `sam deploy`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam deploy`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).

## Deploying applications using sam deploy
<a name="using-sam-cli-deploy-deploying"></a>

When you deploy a serverless application for the first time, use the `--guided` option. The AWS SAM CLI will guide you through an interactive flow to configure your application’s deployment settings.

**To deploy an application using the interactive flow**

1. Go to the root directory of your project. This is the same location as your AWS SAM template.

   ```
   $ cd sam-app
   ```

1. Run the following command:

   ```
   $ sam deploy --guided
   ```

1. During the interactive flow, the AWS SAM CLI prompts you with options to configure your application’s deployment settings.

   Brackets (`[ ]`) indicate default values. Leave your answer blank to select the default value. Default values are obtained from the following configuration files:
   + `~/.aws/config` – Your general AWS account settings.
   + `~/.aws/credentials` – Your AWS account credentials.
   + `<project>/samconfig.toml` – Your project’s configuration file.

   Provide values by answering the AWS SAM CLI prompts. For example, you can enter `y` for **yes**, `n` for **no**, or string values.

   The AWS SAM CLI writes your responses to your project’s `samconfig.toml` file. For subsequent deployments, you can use `sam deploy` to deploy using these configured values. To reconfigure these values, use `sam deploy --guided` again or directly modify your configuration files.

   The following is an example output:

   ```
   sam-app $ 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 [sam-app]: 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]: ENTER
           #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
   ```

1. Next, the AWS SAM CLI deploys your application to the AWS Cloud. During deployment, progress is displayed in your command prompt. The following are the major stages in deployment:
   + For applications with AWS Lambda functions packaged as a .zip file archive, the AWS SAM CLI zips and uploads the package to an Amazon Simple Storage Service (Amazon S3) bucket. If necessary, the AWS SAM CLI will create a new bucket.
   + For applications with Lambda functions package as a container image, the AWS SAM CLI uploads the image to Amazon Elastic Container Registry (Amazon ECR). If necessary, the AWS SAM CLI will create a new repository.
   + The AWS SAM CLI creates an AWS CloudFormation change set and deploys your application to CloudFormation as a stack.
   + The AWS SAM CLI modifies your deployed AWS SAM template with the new `CodeUri` value for your Lambda functions.

   The following is an example of the AWS SAM CLI deployment output:

   ```
           Looking for resources needed for deployment:
   
           Managed S3 bucket: aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
           A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False
   
           Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].
           This parameter will be only saved under [default.global.parameters] in /Users/.../sam-app/samconfig.toml.
   
           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
   
           Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  262144 / 619839  (42.29%)Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  524288 / 619839  (84.58%)Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  619839 / 619839  (100.00%)
   
           Deploying with following values
           ===============================
           Stack name                   : sam-app
           Region                       : us-west-2
           Confirm changeset            : True
           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
   =====================
   
           Uploading to sam-app-zip/be84c20f868068e4dc4a2c11966edf2d.template  1212 / 1212  (100.00%)
   
   
   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                    
   + Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
   + Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                            yment47fc2d5f9d          yment                                           
   + Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                            tage                                                                     
   + Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                     pi                                              
   -------------------------------------------------------------------------------------------------
   
   
   Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680559234/d9f58a77-98bc-41cd-b9f4-433a5a450d7a
   
   
   Previewing CloudFormation changeset before deployment
   ======================================================
   Deploy this changeset? [y/N]: y
   
   2023-04-03 12:00:50 - 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              
   CREATE_COMPLETE          AWS::IAM::Role           HelloWorldFunctionRole   -                      
   CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       -                      
   CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       Resource creation      
                                                                              Initiated              
   CREATE_COMPLETE          AWS::Lambda::Function    HelloWorldFunction       -                      
   CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                            pi                                                                       
   CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        Resource creation      
                            pi                                                Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                            pi                                                                       
   CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                            n                        oWorldPermissionProd                            
   CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                            yment                    yment47fc2d5f9d                                 
   CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   Resource creation      
                            n                        oWorldPermissionProd     Initiated              
   CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   Resource creation      
                            yment                    yment47fc2d5f9d          Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                            yment                    yment47fc2d5f9d                                 
   CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                     tage                                            
   CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   Resource creation      
                                                     tage                     Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                     tage                                            
   CREATE_COMPLETE          AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                            n                        oWorldPermissionProd                            
   CREATE_COMPLETE          AWS::CloudFormation::S   sam-app-zip              -                      
                            tack                                                                     
   -------------------------------------------------------------------------------------------------
   
   CloudFormation outputs from deployed stack
   -------------------------------------------------------------------------------------------------
   Outputs                                                                                         
   -------------------------------------------------------------------------------------------------
   Key                 HelloWorldFunctionIamRole                                                   
   Description         Implicit IAM Role created for Hello World function                          
   Value               arn:aws:iam::012345678910:role/sam-app-zip-                                 
   HelloWorldFunctionRole-11ZOGSCG28H0M                                                            
   
   Key                 HelloWorldApi                                                               
   Description         API Gateway endpoint URL for Prod stage for Hello World function            
   Value               https://njzfhdmls0.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:sam-app-                 
   HelloWorldFunction-XPqNX4TBu7qn                                                                 
   -------------------------------------------------------------------------------------------------
   
   
   Successfully created/updated stack - sam-app-zip in us-west-2
   ```

1. To view your deployed application, do the following:

   1. Open the CloudFormation console directly with the URL [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

   1. Select **Stacks**.

   1. Identify your stack by application name and select it.

### Verify changes before deployment
<a name="using-sam-cli-deploy-deploying-changes"></a>

You can configure the AWS SAM CLI to display your CloudFormation change set and ask for confirmation before deploying.

**To confirm changes before deployment**

1. During `sam deploy --guided`, enter **Y** to confirm changes before deployment.

   ```
   #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
   Confirm changes before deploy [Y/n]: Y
   ```

   Alternatively, you can modify your `samconfig.toml` file with the following:

   ```
   [default.deploy]
   [default.deploy.parameters]
   confirm_changeset = true
   ```

1. During deployment, the AWS SAM CLI will ask you to confirm changes before deployment. The following is an example:

   ```
   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                    
   + Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
   + Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                            yment47fc2d5f9d          yment                                           
   + Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                            tage                                                                     
   + Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                     pi                                              
   -------------------------------------------------------------------------------------------------
   
   Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680559234/d9f58a77-98bc-41cd-b9f4-433a5a450d7a
   Previewing CloudFormation changeset before deployment
   ======================================================
   Deploy this changeset? [y/N]: y
   ```

### Specify additional parameters during deployment
<a name="using-sam-cli-deploy-deploying-params"></a>

You can specify additional parameter values to configure when deploying. You do this by modifying your AWS SAM template and configuring your parameter value during deployment.

**To specify additional parameters**

1. Modify the `Parameters` section of your AWS SAM template. The following is an example:

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   ...
   Globals:
   ...
   Parameters:
     DomainName:
       Type: String
       Default: example
       Description: Domain name
   ```

1. Run `sam deploy --guided`. The following is an example output:

   ```
   sam-app $ 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 [sam-app-zip]: ENTER
           AWS Region [us-west-2]: ENTER
           Parameter DomainName [example]: ENTER
   ```

### Configure code signing for your Lambda functions
<a name="using-sam-cli-deploy-deploying-signing"></a>

You can configure code signing for your Lambda functions at deployment. You do this by modifying your AWS SAM template and configuring code signing during deployment.

**To configure code signing**

1. Specify `CodeSigningConfigArn` in your AWS SAM template. The following is an example:

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   ...
   Resources:
     HelloWorldFunction:
       Type: AWS::Serverless::Function
       Properties:
         CodeUri: hello_world/
         Handler: app.lambda_handler
         Runtime: python3.7
         CodeSigningConfigArn: arn:aws:lambda:us-east-1:111122223333:code-signing-config:csc-12e12345db1234567
   ```

1. Run `sam deploy --guided`. The AWS SAM CLI will prompt you to configure code signing. The following is an example output:

   ```
   #Found code signing configurations in your function definitions
   Do you want to sign your code? [Y/n]: ENTER
   #Please provide signing profile details for the following functions & layers
   #Signing profile details for function 'HelloWorld'
   Signing Profile Name: 
   Signing Profile Owner Account ID (optional):
   #Signing profile details for layer 'MyLayer', which is used by functions {'HelloWorld'}
   Signing Profile Name: 
   Signing Profile Owner Account ID (optional):
   ```

## Best practices
<a name="using-sam-cli-deploy-best"></a>
+ When using `sam deploy`, the AWS SAM CLI deploys your application’s build artifacts located in the `.aws-sam` directory. When you make changes to your application's original files, run `sam build` to update the `.aws-sam` directory before deploying.
+ When deploying an application for the first time, use `sam deploy --guided` to configure deployment settings. For subsequent deployments, you can use `sam deploy` to deploy with your configured settings.

## Options for sam deploy
<a name="using-sam-cli-deploy-options"></a>

The following are commonly used options for `sam deploy`. For a list of all options, see [sam deploy](sam-cli-command-reference-sam-deploy.md).

### Use the guided interactive flow to deploy your application
<a name="using-sam-cli-deploy-options-guided"></a>

Use the `--guided` option to configure your application’s deployment settings through an interactive flow. The following is an example:

```
$ sam deploy --guided
```

Your application’s deployment settings are saved in your project’s `samconfig.toml` file. To learn more, see [Configure project settings](using-sam-cli-configure.md#using-sam-cli-configure-project).

## Troubleshooting
<a name="using-sam-cli-deploy-troubleshooting"></a>

To troubleshoot the AWS SAM CLI, see [AWS SAM CLI troubleshooting](sam-cli-troubleshooting.md).

## Examples
<a name="using-sam-cli-deploy-examples"></a>

### Deploy a Hello World application that contains a Lambda function packaged as a .zip file archive
<a name="using-sam-cli-deploy-examples-example1"></a>

For an example, see [Step 3: Deploy your application to the AWS Cloud](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-deploy) in the Hello World application tutorial.

### Deploy a Hello World application that contains a Lambda function packaged as a container image
<a name="using-sam-cli-deploy-examples-example2"></a>

First, we use `sam init` to create our Hello World application. During the interactive flow, we choose the `Python3.9` runtime and `Image` package type.

```
$ 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]:  ENTER

Which runtime would you like to use?
        1 - aot.dotnet7 (provided.al2)
        ...
        15 - nodejs12.x
        16 - python3.9
        17 - python3.8
        ...
Runtime: 16

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 2

Based on your selections, the only dependency manager available is pip.
We will proceed copying the template using pip.
...
Project name [sam-app]: ENTER

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Base Image: amazon/python3.9-base
    Architectures: x86_64
    Dependency Manager: pip
    Output Directory: .
    Configuration file: sam-app/samconfig.toml

    Next steps can be found in the README file at sam-app/README.md
...
```

Next, we `cd` to the root directory of our project and run `sam build`. The AWS SAM CLI builds our Lambda function locally using Docker.

```
sam-app $ sam build
Building codeuri: /Users/.../sam-app runtime: None metadata: {'Dockerfile': 'Dockerfile', 'DockerContext': '/Users/.../sam-app/hello_world', 'DockerTag': 'python3.9-v1'} architecture: x86_64 functions: HelloWorldFunction
Building image for HelloWorldFunction function
Setting DockerBuildArgs: {} for HelloWorldFunction function
Step 1/5 : FROM public.ecr.aws/lambda/python:3.9
 ---> 0a5e3da309aa
Step 2/5 : COPY requirements.txt ./
 ---> abc4e82e85f9
Step 3/5 : RUN python3.9 -m pip install -r requirements.txt -t .
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in 43845e7aa22d
Collecting requests
  Downloading requests-2.28.2-py3-none-any.whl (62 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 KB 829.5 kB/s eta 0:00:00
Collecting idna<4,>=2.5
  Downloading idna-3.4-py3-none-any.whl (61 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.5/61.5 KB 2.4 MB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
  Downloading charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (199 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 199.2/199.2 KB 2.1 MB/s eta 0:00:00
Collecting certifi>=2017.4.17
  Downloading certifi-2022.12.7-py3-none-any.whl (155 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 155.3/155.3 KB 10.2 MB/s eta 0:00:00
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.15-py2.py3-none-any.whl (140 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.9/140.9 KB 9.1 MB/s eta 0:00:00
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2022.12.7 charset-normalizer-3.1.0 idna-3.4 requests-2.28.2 urllib3-1.26.15
Removing intermediate container 43845e7aa22d
 ---> cab8ace899ce
Step 4/5 : COPY app.py ./
 ---> 4146f3cd69f2
Step 5/5 : CMD ["app.lambda_handler"]
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in f4131ddffb31
Removing intermediate container f4131ddffb31
 ---> d2f5180b2154
Successfully built d2f5180b2154
Successfully tagged helloworldfunction:python3.9-v1


Build Succeeded

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

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

Next, we run `sam deploy --guided` to deploy our application. The AWS SAM CLI guides us through configuring our deployment settings. Then, the AWS SAM CLI deploys our application to the AWS Cloud.

```
sam-app $ 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 [sam-app]: 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]: ENTER
        #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:

        Managed S3 bucket: aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False

        Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].
        This parameter will be only saved under [default.global.parameters] in /Users/.../sam-app/samconfig.toml.

        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

e95fc5e75742: Pushed 
d8df51e7bdd7: Pushed 
b1d0d7e0b34a: Pushed 
0071317b94d8: Pushed 
d98f98baf147: Pushed 
2d244e0816c6: Pushed 
eb2eeb1ebe42: Pushed 
a5ca065a3279: Pushed 
fe9e144829c9: Pushed 
helloworldfunction-d2f5180b2154-python3.9-v1: digest: sha256:cceb71401b47dc3007a7a1e1f2e0baf162999e0e6841d15954745ecc0c447533 size: 2206

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : us-west-2
        Confirm changeset            : True
        Disable rollback             : False
        Deployment image repository  : 
                                       {
                                           "HelloWorldFunction": "012345678910.dkr.ecr.us-west-2.amazonaws.com/samapp7427b055/helloworldfunction19d43fc4repo"
                                       }
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

HelloWorldFunction may not have authorization defined.
        Uploading to sam-app/682ad27c7cf7a17c7f77a1688b0844f2.template  1328 / 1328  (100.00%)


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                    
+ Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
+ Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                         yment47fc2d5f9d          yment                                           
+ Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                         tage                                                                     
+ Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                  pi                                              
-------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680634124/0ffd4faf-2e2b-487e-b9e0-9116e8299ac4


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2023-04-04 08:49:15 - 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::CloudFormation::S   sam-app                  User Initiated         
                         tack                                                                     
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   Resource creation      
                                                                           Initiated              
CREATE_COMPLETE          AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       -                      
CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       Resource creation      
                                                                           Initiated              
CREATE_COMPLETE          AWS::Lambda::Function    HelloWorldFunction       -                      
CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                         pi                                                                       
CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        Resource creation      
                         pi                                                Initiated              
CREATE_COMPLETE          AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                         pi                                                                       
CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                         n                        oWorldPermissionProd                            
CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                         yment                    yment47fc2d5f9d                                 
CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   Resource creation      
                         n                        oWorldPermissionProd     Initiated              
CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   Resource creation      
                         yment                    yment47fc2d5f9d          Initiated              
CREATE_COMPLETE          AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                         yment                    yment47fc2d5f9d                                 
CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                  tage                                            
CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   Resource creation      
                                                  tage                     Initiated              
CREATE_COMPLETE          AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                  tage                                            
CREATE_COMPLETE          AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                         n                        oWorldPermissionProd                            
CREATE_COMPLETE          AWS::CloudFormation::S   sam-app                  -                      
                         tack                                                                     
-------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
-------------------------------------------------------------------------------------------------
Outputs                                                                                         
-------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                   
Description         Implicit IAM Role created for Hello World function                          
Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-JFML1JOKHJ71  

Key                 HelloWorldApi                                                               
Description         API Gateway endpoint URL for Prod stage for Hello World function            
Value               https://endlwiqqod.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:sam-app-HelloWorldFunction-  
kyg6Y2iNRUPg                                                                                    
-------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-app in us-west-2
```

## Learn more
<a name="using-sam-cli-deploy-learn"></a>

To learn more about using the AWS SAM CLI `sam deploy` command, see the following:
+ **[The Complete AWS SAM Workshop: Module 3 - Deploy manually](https://s12d.com/sam-ws-en-manual-deploy)** – Learn how to build, package, and deploy a serverless application using the AWS SAM CLI.

# Options for deploying your application with AWS SAM
<a name="deploying-options"></a>

With AWS SAM, you can deploy your application manually and automate deployments. Use the AWS SAM CLI to manually deploy your application. To automate deployment, use pipelines and a continuous integration and continuous deployment (CI/CD) system. The topics in this section provide information on both approaches.

**Topics**
+ [

## How to use the AWS SAM CLI to manually deploy
](#serverless-sam-cli-using-package-and-deploy)
+ [

## Deploy with CI/CD systems and pipelines
](#serverless-deploying-ci-cd)
+ [

## Gradual deployments
](#serverless-deploying-gradual)
+ [

## Troubleshooting deployments using the AWS SAM CLI
](#serverless-deploying-troubleshooting)
+ [

## Learn more
](#serverless-sam-cli-using-invoke-learn)

## How to use the AWS SAM CLI to manually deploy
<a name="serverless-sam-cli-using-package-and-deploy"></a>

After you develop and test your serverless application locally, you can deploy your application using the **[sam deploy](sam-cli-command-reference-sam-deploy.md)** command.

To have AWS SAM guide you through the deployment with prompts, specify the **--guided** flag. When you specify this flag, the **sam deploy** command zips your application artifacts, uploads them either to Amazon Simple Storage Service (Amazon S3) (for .zip file archives) or to Amazon Elastic Container Registry (Amazon ECR) (for container images). The command then deploys your application to the AWS Cloud.

**Example:**

```
# Deploy an application using prompts:
sam deploy --guided
```

## Deploy with CI/CD systems and pipelines
<a name="serverless-deploying-ci-cd"></a>

AWS SAM helps you automate deployment using pipelines and a continuous integration and continuous deployment (CI/CD) system. AWS SAM can be used to create pipelines and simplify CI/CD tasks for serverless applications. Multiple CI/CD systems support AWS SAM build container images, and AWS SAM also provides a set of default pipeline templates for multiple CI/CD systems that encapsulate AWS's deployment best practices. 

For more information, see [Using CI/CD systems and pipelines to deploy with AWS SAM](deploying-cicd-overview.md).

## Gradual deployments
<a name="serverless-deploying-gradual"></a>

If you want to deploy your AWS SAM application gradually rather than all at once, you can specify deployment configurations that AWS CodeDeploy provides. For more information, see [Working with deployment configurations in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html) in the *AWS CodeDeploy User Guide*.

For information about configuring your AWS SAM application to deploy gradually, see [Deploying serverless applications gradually with AWS SAM](automating-updates-to-serverless-apps.md).

## Troubleshooting deployments using the AWS SAM CLI
<a name="serverless-deploying-troubleshooting"></a>

### AWS SAM CLI error: "Security Constraints Not Satisfied"
<a name="troubleshooting-security-constraints"></a>

When running **sam deploy --guided**, you're prompted with the question `HelloWorldFunction may not have authorization defined, Is this okay? [y/N]`. If you respond to this prompt with **N** (the default response), you see the following error:

```
 
Error: Security Constraints Not Satisfied
```

The prompt is informing you that the application you're about to deploy might have an Amazon API Gateway API configured without authorization. By responding **N** to this prompt, you're saying that this is not OK.

To fix this, you have the following options:
+ Configure your application with authorization. For information about configuring authorization, see [Control API access with your AWS SAM template](serverless-controlling-access-to-apis.md).
+ Respond to this question with **Y** to indicate that you're OK with deploying an application that has an API Gateway API configured without authorization.

## Learn more
<a name="serverless-sam-cli-using-invoke-learn"></a>

For hands-on examples of deploying serverless applications, see the following from *The Complete AWS SAM Workshop*:
+ [Module 3 - Deploy manually](https://s12d.com/sam-ws-en-manual-deploy) – Learn how to build, package, and deploy a serverless application using the AWS SAM CLI.
+ [Module 4 - CI/CD](https://s12d.com/sam-ws-en-cicd-deploy) – Learn how to automate the build, package, and deployment phases by creating a *continuous integration and delivery (CI/CD)* pipeline.

# Using CI/CD systems and pipelines to deploy with AWS SAM
<a name="deploying-cicd-overview"></a>

AWS SAM helps organizations create pipelines for their preferred CI/CD systems, so that they can realize the benefits of CI/CD with minimal effort, such as accelerating deployment frequency, shortening lead time for changes, and reducing deployment errors.

AWS SAM simplifies CI/CD tasks for serverless applications with the help of build container images. The images that AWS SAM provides include the AWS SAM CLI and build tools for a number of supported AWS Lambda runtimes. This makes it easier to build and package serverless applications using the AWS SAM CLI. These images also alleviate the need for teams to create and manage their own images for CI/CD systems. For more information about AWS SAM build container images, see [Image repositories for AWS SAM](serverless-image-repositories.md).

Multiple CI/CD systems support AWS SAM build container images. Which CI/CD system you should use depends on several factors. These include whether your application uses a single runtime or multiple runtimes, or whether you want to build your application within a container image or directly on a host machine, either a virtual machine (VM) or bare metal host.

AWS SAM also provides a set of default pipeline templates for multiple CI/CD systems that encapsulate AWS's deployment best practices. These default pipeline templates use standard JSON/YAML pipeline configuration formats, and the built-in best practices help perform multi-account and multi-region deployments, and verify that pipelines cannot make unintended changes to infrastructure.

You have two main options for using AWS SAM to deploy your serverless applications: 1) Modify your existing pipeline configuration to use AWS SAM CLI commands, or 2) Generate an example CI/CD pipeline configuration that you can use as a starting point for your own application.

**Topics**
+ [

## What is a pipeline?
](#deploying-whatis-pipeline)
+ [

# How AWS SAM uploads local files at deployment
](deploy-upload-local-files.md)
+ [

# Generate a starter CI/CD pipeline with AWS SAM
](serverless-generating-example-ci-cd.md)
+ [

# How to customize starter pipelines with AWS SAM
](serverless-customizing-starter-pipelines.md)
+ [

# Automate the deployment of your AWS SAM application
](serverless-deploying-modify-pipeline.md)
+ [

# How to use OIDC authentication with AWS SAM pipelines
](deploying-with-oidc.md)

## What is a pipeline?
<a name="deploying-whatis-pipeline"></a>

A pipeline is an automated sequence of steps that are performed to release a new version of an application. With AWS SAM, you can use many common CI/CD systems to deploy your applications, including [AWS CodePipeline](https://aws.amazon.com/codepipeline), [Jenkins](https://www.jenkins.io/), [GitLab CI/CD](https://docs.gitlab.com/ee/ci/), and [GitHub Actions](https://github.com/features/actions).

Pipeline templates include AWS deployment best practices to help with multi-account and multi-Region deployments. AWS environments such as dev and production typically exist in different AWS accounts. This allows development teams to configure safe deployment pipelines, without making unintended changes to infrastructure.

You can also supply your own custom pipeline templates to help to standardize pipelines across development teams. 

# How AWS SAM uploads local files at deployment
<a name="deploy-upload-local-files"></a>

When you deploy your application to the AWS Cloud, AWS CloudFormation requires that your local files are first uploaded to an accessible AWS service, such as Amazon Simple Storage Service (Amazon S3). This includes local files your AWS SAM template references. To meet this requirement, the AWS SAM CLI does the following when you use the `sam deploy` or `sam package` command:

1. Automatically uploads your local files to an accessible AWS service.

1. Automatically updates your application template to reference the new file path.

**Topics**
+ [

## Demo: Use the AWS SAM CLI to upload Lambda function code
](#deploy-upload-local-files-demo)
+ [

## Supported use cases
](#deploy-upload-local-files-use)
+ [

## Learn more
](#deploy-upload-local-files-learn)

## Demo: Use the AWS SAM CLI to upload Lambda function code
<a name="deploy-upload-local-files-demo"></a>

In this demo, we initialize the sample Hello World application using a .zip package type for our Lambda function. We use the AWS SAM CLI to automatically upload our Lambda function code to Amazon S3 and reference its new path in our application template.

First, we run `sam init` to initialize our Hello World application.

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

Our Lambda function code is organized in the `hello_world` subdirectory of our project.

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

Within our AWS SAM template, we reference the local path to our Lambda function code using the `CodeUri` property.

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

Next, we run `sam build` to build our application and prepare for deployment.

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

Next, we run `sam deploy --guided` to deploy our application.

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

During deployment, the AWS SAM CLI automatically uploads our Lambda function code to Amazon S3 and updates our template. Our modified template in the CloudFormation console reflects the Amazon S3 bucket path.

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

## Supported use cases
<a name="deploy-upload-local-files-use"></a>

The AWS SAM CLI can automatically facilitate this process for a number of file types, CloudFormation resource types, and CloudFormation macros.

### File types
<a name="deploy-upload-local-files-use-types"></a>

Application files and Docker images are supported.

### CloudFormation resource types
<a name="deploy-upload-local-files-use-resources"></a>

The following is a list of the supported resource types and their properties:


| Resource | 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 macros
<a name="deploy-upload-local-files-use-macros"></a>

Files referenced using the `AWS::Include` transform macro are supported.

## Learn more
<a name="deploy-upload-local-files-learn"></a>

To learn more about the `AWS::Include` transform, see [ AWS::Include transform](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html) in the *AWS CloudFormation User Guide*.

To see an example of using the `AWS::Include` transform in an AWS SAM template, see the [API Gateway HTTP API to SQS](https://serverlessland.com/patterns/apigw-sqs) pattern at * Serverless Land*.

# Generate a starter CI/CD pipeline with AWS SAM
<a name="serverless-generating-example-ci-cd"></a>

When you are ready automate deployment, you can use one of AWS SAM’s starter pipeline templates to generate a deployment pipeline for the CI/CD system you choose to use. Your deployment pipeline is what you configure and use to automate the deployment of your serverless application. A starter pipeline template is pre-configured to help you quickly set up your deployment pipeline for your serverless application. 

With a starter pipeline template, you can generate pipelines in minutes using the [sam pipeline init](sam-cli-command-reference-sam-pipeline-init.md) command.

The starter pipeline templates use the familiar JSON/YAML syntax of the CI/CD system, and incorporate best practices such as managing artifacts across multiple accounts and regions, and using the minimum amount of permissions required to deploy the application. Currently, the AWS SAM CLI supports generating starter CI/CD pipeline configurations for [AWS CodePipeline](https://aws.amazon.com/codepipeline), [Jenkins](https://www.jenkins.io/), [GitLab CI/CD](https://docs.gitlab.com/ee/ci/), [GitHub Actions](https://github.com/features/actions), and [Bitbucket Pipelines](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/).

Here are the high-level tasks you need to perform to generate a starter pipeline configuration:

1. **Create infrastructure resources** – Your pipeline requires certain AWS resources, for example the IAM user and roles with necessary permissions, an Amazon S3 bucket, and optionally an Amazon ECR repository.

1. **Connect your Git repository with your CI/CD system** – Your CI/CD system needs to know which Git repository will trigger the pipeline to run. Note that this step may not be necessary, depending on which combination of Git repository and CI/CD system you are using.

1. **Generate your pipeline configuration** – This step generates a starter pipeline configuration that includes two deployment stages.

1. **Commit your pipeline configuration to your Git repository** – This step is necessary to ensure your CI/CD system is aware of your pipeline configuration, and will run when changes are committed.

After you've generated the starter pipeline configuration and committed it to your Git repository, whenever someone commits a code change to that repository your pipeline will be triggered to run automatically.

The ordering of these steps, and details of each step, vary based on your CI/CD system:
+ If you are using AWS CodePipeline, see [Generating starter pipeline for AWS CodePipeline in AWS SAM](serverless-generating-example-ci-cd-codepipeline.md).
+ If you are using Jenkins, GitLab CI/CD, GitHub Actions, or Bitbucket Pipelines, see [Use AWS SAM to generate starter pipelines for Jenkins, GitLab CI/CD, GitHub Actions, Bitbucket Pipelines](serverless-generating-example-ci-cd-others.md).

# Generating starter pipeline for AWS CodePipeline in AWS SAM
<a name="serverless-generating-example-ci-cd-codepipeline"></a>

To generate a starter pipeline configuration for AWS CodePipeline, perform the following tasks in this order:

1. Create infrastructure resources

1. Generate the pipeline configuration

1. Commit your pipeline configuration to Git

1. Connect your Git repository with your CI/CD system

**Note**  
The following procedure utilizes two AWS SAM CLI commands, `sam pipeline bootstrap` and `sam pipeline init`. The reason there are two commands is to handle the use case where administrators (that is, users who need permission to set up infrastructure AWS resource like IAM users and roles) have more permission that developers (that is, users who just need permission to set up individual pipelines, but not the required infrastructure AWS resources).

## Step 1: Create infrastructure resources
<a name="generating-example-step-1"></a>

Pipelines that use AWS SAM require certain AWS resources, like an IAM user and roles with necessary permissions, an Amazon S3 bucket, and optionally an Amazon ECR repository. You must have a set of infrastructure resources for each deployment stage of the pipeline.

You can run the following command to help with this setup:

```
sam pipeline bootstrap
```

**Note**  
Run the previous command for each deployment stage of your pipeline.

## Step 2: Generate the pipeline configuration
<a name="generating-example-step-2"></a>

To generate the pipeline configuration, run the following command:

```
sam pipeline init
```

## Step 3: Commit your pipeline configuration to Git repository
<a name="generating-example-step-3"></a>

This step is necessary to ensure your CI/CD system is aware of your pipeline configuration, and will run when changes are committed.

## Step 4: Connect your Git repository with your CI/CD system
<a name="generating-example-step-4"></a>

For AWS CodePipeline you can now create the connection by running the following command:

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

If you are using GitHub or Bitbucket, after running the **sam deploy** command previously, complete the connection by following the steps under **To complete a connection** found on the [Update a pending connection](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html) topic in the *Developer Tools console user guide*. In addition, store a copy of the `CodeStarConnectionArn` from the output of the **sam deploy** command, because you will need it if you want to use AWS CodePipeline with another branch than `main`.

## Configuring other branches
<a name="configuring-other-branches"></a>

By default, AWS CodePipeline uses the `main` branch with AWS SAM. If you want to use a branch other than `main`, you must run the **sam deploy** command again. Note that depending on which Git repository you are using, you may also need to provide the `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>"
```

## Learn more
<a name="serverless-generating-cicd-learn"></a>

For a hands-on example of setting up a CI/CD pipeline, see [ CI/CD with AWS CodePipeline](https://catalog.workshops.aws/complete-aws-sam/en-US/module-4-cicd) in *The Complete AWS SAM Workshop*.

# Use AWS SAM to generate starter pipelines for Jenkins, GitLab CI/CD, GitHub Actions, Bitbucket Pipelines
<a name="serverless-generating-example-ci-cd-others"></a>

To generate a starter pipeline configuration for Jenkins, GitLab CI/CD, GitHub Actions, or Bitbucket Pipelines perform the following tasks in this order:

1. Create infrastructure resources

1. Connect your Git repository with your CI/CD system

1. Create credential objects

1. Generate the pipeline configuration

1. Commit your pipeline configuration to Git repository

**Note**  
The following procedure utilizes two AWS SAM CLI commands, `sam pipeline bootstrap` and `sam pipeline init`. The reason there are two commands is to handle the use case where administrators (that is, users who need permission to set up infrastructure AWS resource like IAM users and roles) have more permission that developers (that is, users who just need permission to set up individual pipelines, but not the required infrastructure AWS resources).

## Step 1: Create infrastructure resources
<a name="generating-example-step-1"></a>

Pipelines that use AWS SAM require certain AWS resources, like an IAM user and roles with necessary permissions, an Amazon S3 bucket, and optionally an Amazon ECR repository. You must have a set of infrastructure resources for each deployment stage of the pipeline.

You can run the following command to help with this setup:

```
sam pipeline bootstrap
```

**Note**  
Run the previous command for each deployment stage of your pipeline.

You must capture the AWS credentials (key id and secret key) for the pipeline users for each deployment stage of your pipeline, because they are needed for subsequent steps.

## Step 2: Connect your Git repository with your CI/CD system
<a name="generating-example-step-2"></a>

Connecting your Git repository to your CI/CD system is necessary so that the CI/CD system is able to access your application source code for builds and deployments.

**Note**  
You can skip this step if you are using one of the following combinations, because the connection is done for you automatically:  
GitHub Actions with GitHub repository
GitLab CI/CD with GitLab repository
Bitbucket Pipelines with a Bitbucket repository

To connect your Git repository with your CI/CD system, do one of the following:
+ If you're using Jenkins, see the [Jenkins documentation](https://www.jenkins.io/doc/book/pipeline/multibranch/) for "Adding a branch source."
+ If you're using GitLab CI/CD and a Git repository other than GitLab, see the [GitLab documentation](https://docs.gitlab.com/ee/ci/ci_cd_for_external_repos/) for "connecting an external repository."

## Step 3: Create credential objects
<a name="generating-example-step-3"></a>

Each CI/CD system has its own way of managing credentials needed for the CI/CD system to access your Git repository.

To create the necessary credential objects, do one of the following:
+ If you're using Jenkins, create a single "credential" that stores both the key id and secret key. Follow the instructions in the [Building a Jenkins Pipeline with AWS SAM](https://aws.amazon.com/blogs/compute/building-a-jenkins-pipeline-with-aws-sam/) blog, in the **Configure Jenkins** section. You will need the "Credential id" for the next step.
+ If you're using GitLab CI/CD, create two "protected variables", one for each of key id and secret key. Follow the instructions in the [GitLab documentation](https://docs.gitlab.com/ee/ci/variables/) – you will need two "variable keys" for the next step.
+ If you're using GitHub Actions, create two "encrypted secrets", one for each of key and secret key. Follow the instructions in the [GitHub documentation](https://docs.github.com/en/actions/reference/encrypted-secrets) - you will need two "secret names" for the next step.
+ If you're using Bitbucket Pipelines, create two "secure variables", one for each of key id and secret key. Follow the instructions in the [Variables and secrets ](https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets) - you will need two "secret names" for the next step.

## Step 4: Generate the pipeline configuration
<a name="generating-example-step-4"></a>

To generate the pipeline configuration, run the following command. You will need to input the credential object that you created in the previous step:

```
sam pipeline init
```

## Step 5: Commit your pipeline configuration to Git repository
<a name="generating-example-step-5"></a>

This step is necessary to ensure your CI/CD system is aware of your pipeline configuration, and will run when changes are committed.

## Learn more
<a name="serverless-generating-other-cicd-learn"></a>

For a hands-on example of setting up a CI/CD pipeline using GitHub Actions, see [CI/CD with GitHub](https://s12d.com/sam-ws-en-gh) in *The Complete AWS SAM Workshop*.

# How to customize starter pipelines with AWS SAM
<a name="serverless-customizing-starter-pipelines"></a>

As a CI/CD administrator, you may want to customize a starter pipeline template, and associated guided prompts, that developers in your organization can use to create pipeline configurations.

The AWS SAM CLI uses Cookiecutter templates when creating starter templates. For details about cookie cutter templates, [Cookiecutter](https://cookiecutter.readthedocs.io/en/latest/README.html).

You can also customize the prompts that the AWS SAM CLI displays to users when creating pipeline configurations using the `sam pipeline init` command. To customize user prompts, do the following:

1. **Create a `questions.json` file** – The `questions.json` file must be in the root of the project respository. This is the same directory as the `cookiecutter.json` file. To view the schema for the `questions.json` file, see [questions.json.schema](https://github.com/aws/aws-sam-cli/blob/2b831b29f76ac9c4e0cbcbd68b37f8f664e136d8/samcli/lib/pipeline/init/questions.json.schema). To view an example `questions.json` file, see [questions.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/questions.json).

1. **Map question keys with cookiecutter names** – Each object in the `questions.json` file needs a key that matches a name in the cookiecutter template. This key matching is how the AWS SAM CLI maps user prompt responses to the cookie cutter template. To see examples of this key matching, see the [Example files](#serverless-customizing-starter-pipelines-example-files) section later in this topic. 

1. **Create a `metadata.json` file** – Declare the number of stages the pipeline will have in the `metadata.json` file. The number of stages instructs the `sam pipeline init` command how many stages to prompt information about, or in the case of the `--bootstrap` option, how many stages to create infrastructure resources for. To view an example `metadata.json` file that declares a pipeline with two stages, see [metadata.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/metadata.json).

## Example projects
<a name="serverless-customizing-starter-pipelines-example-projects"></a>

Here are example projects, which each include a Cookiecutter template, a `questions.json` file, and a `metadata.json` file:
+ Jenkins example: [Two-stage Jenkins pipeline template](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/Jenkins/two-stage-pipeline-template)
+ CodePipeline example: [Two stage CodePipeline pipeline template](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/AWS-CodePipeline/two-stage-pipeline-template)

## Example files
<a name="serverless-customizing-starter-pipelines-example-files"></a>

The following set of files show how questions in the `questions.json` file are associated with entries in the Cookiecutter template file. Note that these examples are file snippets, not full files. To see examples of full files, see the [Example projects](#serverless-customizing-starter-pipelines-example-projects) section earlier in this topic.

Example **`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"
  }, {
    ...
```

Example **`cookiecutter.json`**:

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

Example **`Jenkinsfile`**:

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

# Automate the deployment of your AWS SAM application
<a name="serverless-deploying-modify-pipeline"></a>

In AWS SAM, how you automate the deployment of your AWS SAM application varies depending on the CI/CD system you are using. For this reason, the examples in this section show you how to configure various CI/CD systems to automate building serverless applications in an AWS SAM build container image. These build container images make it easier to build and package serverless applications using the AWS SAM CLI.

The procedures for your existing CI/CD pipeline to deploy serverless applications using AWS SAM are slightly different depending on which CI/CD system you are using.

The following topics provide examples for configuring your CI/CD system to build serverless applications within an AWS SAM build container image:

**Topics**
+ [

# Using AWS CodePipeline to deploy with AWS SAM
](deploying-using-codepipeline.md)
+ [

# Using Bitbucket Pipelines to deploying with AWS SAM
](deploying-using-bitbucket.md)
+ [

# Using Jenkins to deploy with AWS SAM
](deploying-using-jenkins.md)
+ [

# Using GitLab CI/CD to deploy with AWS SAM
](deploying-using-gitlab.md)
+ [

# Using GitHub Actions to deploy with AWS SAM
](deploying-using-github.md)

# Using AWS CodePipeline to deploy with AWS SAM
<a name="deploying-using-codepipeline"></a>

To configure your [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) pipeline to automate the build and deployment of your AWS SAM application, your CloudFormation template and `buildspec.yml` file must contain lines that do the following:

1. Reference a build container image with the necessary runtime from the available images. The following example uses the `public.ecr.aws/sam/build-nodejs20.x` build container image.

1. Configure the pipeline stages to run the necessary AWS SAM command line interface (CLI) commands. The following example runs two AWS SAM CLI commands: **sam build** and **sam deploy** (with necessary options).

This example assumes that you have declared all functions and layers in your AWS SAM template file with `runtime: nodejs20.x`.

**CloudFormation template snippet:**

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

**`buildspec.yml` snippet:**

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

For a list of available Amazon Elastic Container Registry (Amazon ECR) build container images for different runtimes, see [Image repositories for AWS SAM](serverless-image-repositories.md).

# Using Bitbucket Pipelines to deploying with AWS SAM
<a name="deploying-using-bitbucket"></a>

To configure your [Bitbucket Pipeline](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/) to automate the build and deployment of your AWS SAM application, your `bitbucket-pipelines.yml` file must contain lines that do the following:

1. Reference a build container image with the necessary runtime from the available images. The following example uses the `public.ecr.aws/sam/build-nodejs20.x` build container image.

1. Configure the pipeline stages to run the necessary AWS SAM command line interface (CLI) commands. The following example runs two AWS SAM CLI commands: **sam build** and **sam deploy** (with necessary options).

This example assumes that you have declared all functions and layers in your AWS SAM template file with `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
```

For a list of available Amazon Elastic Container Registry (Amazon ECR) build container images for different runtimes, see [Image repositories for AWS SAM](serverless-image-repositories.md).

# Using Jenkins to deploy with AWS SAM
<a name="deploying-using-jenkins"></a>

To configure your [Jenkins](https://www.jenkins.io/) pipeline to automate the build and deployment of your AWS SAM application, your `Jenkinsfile` must contain lines that do the following:

1. Reference a build container image with the necessary runtime from the available images. The following example uses the `public.ecr.aws/sam/build-nodejs20.x` build container image.

1. Configure the pipeline stages to run the necessary AWS SAM command line interface (CLI) commands. The following example runs two AWS SAM CLI commands: **sam build** and **sam deploy** (with necessary options).

This example assumes that you have declared all functions and layers in your AWS SAM template file with `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'
            }
        }
    }
}
```

For a list of available Amazon Elastic Container Registry (Amazon ECR) build container images for different runtimes, see [Image repositories for AWS SAM](serverless-image-repositories.md).

# Using GitLab CI/CD to deploy with AWS SAM
<a name="deploying-using-gitlab"></a>

To configure your [GitLab](https://about.gitlab.com) pipeline to automate the build and deployment of your AWS SAM application, your `gitlab-ci.yml` file must contain lines that do the following:

1. Reference a build container image with the necessary runtime from the available images. The following example uses the `public.ecr.aws/sam/build-nodejs20.x` build container image.

1. Configure the pipeline stages to run the necessary AWS SAM command line interface (CLI) commands. The following example runs two AWS SAM CLI commands: **sam build** and **sam deploy** (with necessary options).

This example assumes that you have declared all functions and layers in your AWS SAM template file with `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
```

For a list of available Amazon Elastic Container Registry (Amazon ECR) build container images for different runtimes, see [Image repositories for AWS SAM](serverless-image-repositories.md).

# Using GitHub Actions to deploy with AWS SAM
<a name="deploying-using-github"></a>

To configure your [GitHub](https://github.com/) pipeline to automate the build and deployment of your AWS SAM application, you must first install the AWS SAM command line interface (CLI) on your host. You can use [GitHub Actions](https://github.com/features/actions) in your GitHub workflow to help with this setup.

The following example GitHub workflow sets up an Ubuntu host using a series of GitHub Actions, then runs AWS SAM CLI commands to build and deploy an AWS SAM application:

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

For a list of available Amazon Elastic Container Registry (Amazon ECR) build container images for different runtimes, see [Image repositories for AWS SAM](serverless-image-repositories.md).

# How to use OIDC authentication with AWS SAM pipelines
<a name="deploying-with-oidc"></a>

AWS Serverless Application Model (AWS SAM) supports OpenID Connect (OIDC) user authentication for Bitbucket, GitHub Actions, and GitLab continuous integration and continuous delivery (CI/CD) platforms. With this support, you can use authorized CI/CD user accounts from any of these platforms to manage your serverless application pipelines. Otherwise, you would need to create and manage multiple AWS Identity and Access Management (IAM) users to control access to AWS SAM pipelines.

## Set up OIDC with AWS SAM pipeline
<a name="deploying-with-oidc-setup"></a>

During the `sam pipeline bootstrap` configuration process, do the following to set up OIDC with your AWS SAM pipeline.

1. When prompted to choose an identity provider, select **OIDC**.

1. Next, select a supported OIDC provider.

1. Enter the OIDC provider URL, beginning with **https://**.
**Note**  
AWS SAM references this URL when it generates the `AWS::IAM::OIDCProvider` resource type.

1. Next, follow the prompts and enter the CI/CD platform information needed to access the selected platform. These details vary by platform and can include:
   + OIDC client ID.
   + Code repository name or universally unique identifier (UUID).
   + Group or Organization name associated with the repository.
   + GitHub organization that the code repository belongs to.
   + GitHub repository name.
   + Branch that deployments will occur from.

1. AWS SAM displays a summary of the entered OIDC configuration. Enter the number for a setting to edit it, or press Enter to continue.

1. When prompted to confirm the creation of resources needed to support the entered OIDC connection, press Y to continue.

AWS SAM generates an `AWS::IAM::OIDCProvider` AWS CloudFormation resource with the provided configuration that assumes the pipeline execution role. To learn more about this CloudFormation resource type, see [AWS::IAM::OIDCProvider](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-oidcprovider.html) in the *AWS CloudFormation User Guide*.

**Note**  
If the identity provider (IdP) resource already exists in your AWS account, AWS SAM references it instead of creating a new resource.

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

The following is an example of setting up OIDC with AWS SAM pipeline.

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

## Learn more
<a name="deploying-with-oidc-setup-learn-more"></a>

For more information on using OIDC with AWS SAM pipeline, see [sam pipeline bootstrap](sam-cli-command-reference-sam-pipeline-bootstrap.md).

# Introduction to using sam sync to sync to AWS Cloud
<a name="using-sam-cli-sync"></a>

The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam sync` command provides options to quickly sync local application changes to the AWS Cloud. Use `sam sync` when developing your applications to:

1. Automatically detect and sync local changes to the AWS Cloud.

1. Customize what local changes are synced to the AWS Cloud.

1. Prepare your application in the cloud for testing and validation.

With `sam sync`, you can create a rapid development workflow that shortens the time it takes to sync your local changes to the cloud for testing and validation.

**Note**  
The `sam sync` command is recommended for development environments. For production environments, we recommend using `sam deploy` or configuring a *continuous integration and delivery (CI/CD)* pipeline. To learn more, see [Deploy your application and resources with AWS SAM](serverless-deploying.md).

The `sam sync` command is a part of AWS SAM Accelerate. *AWS SAM Accelerate* provides tools that you can use to speed up the experience of developing and testing serverless applications in the AWS Cloud.

**Topics**
+ [

## Automatically detect and sync local changes to the AWS Cloud
](#using-sam-cli-sync-auto)
+ [

## Customize what local changes are synced to the AWS Cloud
](#using-sam-cli-sync-customize)
+ [

## Prepare your application in the cloud for testing and validation
](#using-sam-cli-sync-test)
+ [

## Options for the sam sync command
](#using-sam-cli-sync-options)
+ [

## Troubleshooting
](#using-sam-cli-sync-troubleshooting)
+ [

## Examples
](#using-sam-cli-sync-examples)
+ [

## Learn more
](#using-sam-cli-sync-learn)

## Automatically detect and sync local changes to the AWS Cloud
<a name="using-sam-cli-sync-auto"></a>

Run `sam sync` with the `--watch` option to begin syncing your application to the AWS Cloud. This does the following:

1. **Build your application ** – This process is similar to using the `sam build` command.

1. **Deploy your application** – The AWS SAM CLI deploys your application to AWS CloudFormation using your default settings. The following default values are used:

   1. AWS credentials and general configuration settings found in your `.aws` user folder.

   1. Application deployment settings found in your application’s `samconfig.toml` file.

   If default values can’t be found, the AWS SAM CLI will inform you and exit the sync process.

1. **Watch for local changes** – The AWS SAM CLI remains running and watches for local changes to your application. This is what the `--watch` option provides.

   This option may be turned on by default. For default values, see your application’s `samconfig.toml` file. The following is an example file:

   ```
   ...
   [default.sync]
   [default.sync.parameters]
   watch = true
   ...
   ```

1. **Sync local changes to the AWS Cloud** – When you make local changes, the AWS SAM CLI detects and syncs those changes to the AWS Cloud through the quickest method available. Depending on the type of change, the following may occur:

   1. If your updated resource supports AWS service APIs, the AWS SAM CLI will use it to deploy your changes. This results in a quick sync to update your resource in the AWS Cloud.

   1. If your updated resource doesn’t support AWS service APIs, the AWS SAM CLI will perform an CloudFormation deployment. This updates your entire application in the AWS Cloud. While not as quick, it does prevent you from having to manually initiate a deployment.

Since the `sam sync` command automatically updates your application in the AWS Cloud, it is recommended for development environments only. When you run `sam sync`, you will be asked to confirm:

```
**The sync command should only be used against a development stack**.

Confirm that you are synchronizing a development stack.

Enter Y to proceed with the command, or enter N to cancel:
 [Y/n]: ENTER
```

## Customize what local changes are synced to the AWS Cloud
<a name="using-sam-cli-sync-customize"></a>

Provide options to customize what local changes are synced to the AWS Cloud. This can speed up the time it takes to see your local changes in the cloud for testing and validation.

For example, provide the `--code` option to sync only code changes, such as AWS Lambda function code. During development, if you are focused specifically on Lambda code, this will get your changes into the cloud quickly for testing and validation. The following is an example:

```
$ sam sync --code --watch
```

To sync only code changes for a specific Lambda function or layer, use the `--resource-id` option. The following is an example:

```
$ sam sync --code --resource-id HelloWorldFunction --resource-id HelloWorldLayer
```

## Prepare your application in the cloud for testing and validation
<a name="using-sam-cli-sync-test"></a>

The `sam sync` command automatically finds the quickest method available to update your application in the AWS Cloud. This can speed up your development and cloud testing workflows. By utilizing AWS service APIs, you can quickly develop, sync, and test supported resources. For a hands-on example, see [Module 6 - AWS SAM Accelerate](https://s12d.com/sam-ws-en-accelerate) in *The Complete AWS SAM Workshop*.

## Options for the sam sync command
<a name="using-sam-cli-sync-options"></a>

The following are some of the main options you can use to modify the `sam sync` command. For a list of all options, see [sam sync](sam-cli-command-reference-sam-sync.md).

### Perform a one-time CloudFormation deployment
<a name="using-sam-cli-sync-options-single-deploy"></a>

Use the `--no-watch` option to turn off automatic syncing. The following is an example:

```
$ sam sync --no-watch
```

The AWS SAM CLI will perform a one-time CloudFormation deployment. This command groups together the actions performed by the `sam build` and `sam deploy` commands.

### Skip the initial CloudFormation deployment
<a name="using-sam-cli-sync-options-skip-deploy-sync"></a>

You can customize whether an CloudFormation deployment is required each time `sam sync` is run.
+ Provide `--no-skip-deploy-sync` to require an CloudFormation deployment each time `sam sync` is run. This ensures that your local infrastructure is synced to CloudFormation, preventing drift. Using this option does add additional time to your development and testing workflow.
+ Provide `--skip-deploy-sync` to make CloudFormation deployment optional. The AWS SAM CLI will compare your local AWS SAM template with your deployed CloudFormation template and will skip the initial CloudFormation deployment if a change isn't detected. Skipping CloudFormation deployment can save you time when syncing local changes to the AWS Cloud.

  If no change is detected, the AWS SAM CLI will still perform an CloudFormation deployment in the following scenarios:
  + If its been 7 days or more since your last CloudFormation deployment.
  + If a large number of Lambda function code changes are detected, making CloudFormation deployment the quickest method to update your application.

The following is an example:

```
$ sam sync --skip-deploy-sync
```

### Sync a resource from a nested stack
<a name="using-sam-cli-sync-options-nested-stack"></a>

**To sync a resource from a nested stack**

1. Provide the root stack using `--stack-name`.

1. Identify the resource in the nested stack using the following format: `nestedStackId/resourceId`.

1. Provide the resource in the nested stack using `--resource-id`.

   The following is an example:

   ```
   $ sam sync --code --stack-name sam-app --resource-id myNestedStack/HelloWorldFunction
   ```

For more information about creating nested applications, see [Reuse code and resources using nested applications in AWS SAM](serverless-sam-template-nested-applications.md).

### Specify a specific CloudFormation stack to update
<a name="using-sam-cli-sync-options-stack-name"></a>

To specify a specific CloudFormation stack to update, provide the `--stack-name` option. The following is an example:

```
$ sam sync --stack-name dev-sam-app
```

### Speed up build times by building your project in the source folder
<a name="using-sam-cli-sync-options-source"></a>

For supported runtimes and build methods, you can use the `--build-in-source` option to build your project directly in the source folder. By default, the AWS SAM CLI builds in a temporary directory, which involves copying over source code and project files. With `--build-in-source`, the AWS SAM CLI builds directly in your source folder, which speeds up the build process by removing the need to copy files to a temporary directory.

For a list of supported runtimes and build methods, see ` --build-in-source`.

### Specify files and folders that won't initiate a sync
<a name="using-sam-cli-sync-options-exclude"></a>

Use the `--watch-exclude` option to specify any file or folder that won't initiate a sync when updated. For more information about this option, see `--watch-exclude`.

The following is an example that excludes the `package-lock.json` file associated with our `HelloWorldFunction` function:

```
$ sam sync --watch --watch-exclude HelloWorldFunction=package-lock.json
```

When this command is run, the AWS SAM CLI will initiate the sync process. This includes the following:
+ Run `sam build` to build your functions and prepare your application for deployment.
+ Run `sam deploy` to deploy your application.
+ Watch for changes to your application.

When we modify the `package-lock.json` file, the AWS SAM CLI won't initiate a sync. When another file is updated, the AWS SAM CLI will initiate a sync, which will include the `package-lock.json` file.

The following is an example of specifying a Lambda function of a child stack:

```
$ sam sync --watch --watch-exclude ChildStackA/MyFunction=database.sqlite3
```

## Troubleshooting
<a name="using-sam-cli-sync-troubleshooting"></a>

To troubleshoot the AWS SAM CLI, see [AWS SAM CLI troubleshooting](sam-cli-troubleshooting.md).

## Examples
<a name="using-sam-cli-sync-examples"></a>

### Using sam sync to update the Hello World application
<a name="using-sam-cli-sync-examples-example1"></a>

In this example, we start by initializing the sample Hello World application. To learn more about this application, see [Tutorial: Deploy a Hello World application with AWS SAM](serverless-getting-started-hello-world.md).

Running `sam sync` begins the build and deployment process.

```
$ sam sync
				
The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without
performing a CloudFormation deployment. This will cause drift in your CloudFormation stack.
**The sync command should only be used against a development stack**.

Confirm that you are synchronizing a development stack.

Enter Y to proceed with the command, or enter N to cancel:
 [Y/n]:
Queued infra sync. Waiting for in progress code syncs to complete...
Starting infra sync.
Manifest file is changed (new hash: 3298f13049d19cffaa37ca931dd4d421) or dependency folder (.aws-sam/deps/0663e6fe-a888-4efb-b908-e2344261e9c7) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
Building codeuri: /Users/.../Demo/sync/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CleanUp
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpx_5t4u3f.
Execute the following command to deploy the packaged template
sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpx_5t4u3f --stack-name <YOUR STACK NAME>


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

Initiating deployment
=====================


2023-03-17 11:17:19 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          sam-app                             Transformation succeeded
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
CREATE_IN_PROGRESS                  AWS::IAM::Role                      HelloWorldFunctionRole              -
CREATE_IN_PROGRESS                  AWS::IAM::Role                      HelloWorldFunctionRole              Resource creation Initiated
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   Resource creation Initiated
                                                                        ack
CREATE_COMPLETE                     AWS::IAM::Role                      HelloWorldFunctionRole              -
CREATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
CREATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
CREATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  Resource creation Initiated
CREATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
CREATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   Resource creation Initiated
CREATE_COMPLETE                     AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
CREATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Resource creation Initiated
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   Resource creation Initiated
                                                                        5f9d
CREATE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
CREATE_IN_PROGRESS                  AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
CREATE_IN_PROGRESS                  AWS::ApiGateway::Stage              ServerlessRestApiProdStage          Resource creation Initiated
CREATE_COMPLETE                     AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
CREATE_COMPLETE                     AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
CREATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
---------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
----------------------------------------------------------------------------------------------------------------------------------------------
Outputs
----------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole
Description         Implicit IAM Role created for Hello World function
Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-BUFVMO2PJIYF

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://pcrx5gdaof.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:sam-app-HelloWorldFunction-2PlN6TPTQoco
----------------------------------------------------------------------------------------------------------------------------------------------
Stack creation succeeded. Sync infra completed.

Infra sync completed.
CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.
```

Once deployment is complete, we modify the `HelloWorldFunction` code. The AWS SAM CLI detects this change and syncs our application to the AWS Cloud. Since AWS Lambda supports AWS service APIs, a quick sync is performed.

```
Syncing Lambda Function HelloWorldFunction...
Manifest is not changed for (HelloWorldFunction), running incremental build
Building codeuri: /Users/.../Demo/sync/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CopySource
Finished syncing Lambda Function HelloWorldFunction.
```

Next, we modify our API endpoint in the application’s AWS SAM template. We change `/hello` to `/helloworld`.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    ...
    Properties:
      ...
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /helloworld
            Method: get
```

Since the Amazon API Gateway resource doesn’t support the AWS service API, the AWS SAM CLI automatically performs an CloudFormation deployment. The following is an example output:

```
Queued infra sync. Waiting for in progress code syncs to complete...
Starting infra sync.
Manifest is not changed for (HelloWorldFunction), running incremental build
Building codeuri: /Users/.../Demo/sync/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CopySource

Build Succeeded

Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpuabo0jb9.
Execute the following command to deploy the packaged template
sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpuabo0jb9 --stack-name <YOUR STACK NAME>


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

Initiating deployment
=====================


2023-03-17 14:41:18 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------------------------------
UPDATE_IN_PROGRESS                  AWS::CloudFormation::Stack          sam-app                             Transformation succeeded
UPDATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
UPDATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
UPDATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   -
UPDATE_COMPLETE                     AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   -
                                                                        d3cd
UPDATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Requested update requires the
                                                                        ssionProd                           creation of a new physical
                                                                                                            resource; hence creating one.
UPDATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Resource creation Initiated
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   Resource creation Initiated
                                                                        d3cd
CREATE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   -
                                                                        d3cd
UPDATE_IN_PROGRESS                  AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
UPDATE_COMPLETE                     AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
UPDATE_COMPLETE                     AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
SS
DELETE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
DELETE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
DELETE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
UPDATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
DELETE_COMPLETE                     AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
UPDATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
---------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
----------------------------------------------------------------------------------------------------------------------------------------------
Outputs
----------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole
Description         Implicit IAM Role created for Hello World function
Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-BUFVMO2PJIYF

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://pcrx5gdaof.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:sam-app-HelloWorldFunction-2PlN6TPTQoco
----------------------------------------------------------------------------------------------------------------------------------------------


Stack update succeeded. Sync infra completed.

Infra sync completed.
```

## Learn more
<a name="using-sam-cli-sync-learn"></a>

For a description of all `sam sync` options, see [sam sync](sam-cli-command-reference-sam-sync.md).