Building deployment pipelines on AWS Cloud has never been easy with SAM CLI

AWS SAM Pipeline is a new capability in AWS SAM CLI. It makes it easier to auto-generate secure, continuous integration and deployment pipelines for your organization’s CI/CD system. AWS SAM Pipelines provides templates for popular CI/CD systems such as AWS CodePipeline, Jenkins, GitHub Actions, and GitLab CI/CD.

Solution

In this blog, I will show you how to use AWS SAM pipelines to create a multi-stage deployment pipeline with AWS CodeCommit, CodeBuild, CodeDeploy, and CodePipeline services.

Prerequisite

  • An active AWS account.
  • AWS CLI is an open source tool that enables you to interact with AWS services using commands in your command-line shell. To install and configure the AWS CLI, follow the official documentation.
  • AWS SAM CLI is a command-line tool that operates on an AWS SAM template and application code. To install SAM CLI, please follow the AWS official documentation.
  • Git Client to access the Code Commit repository from the bash shell.

Step 1: Create a Code Commit git Repository

Any CI/CD pipeline starts with a code repository, let’s creates a code commit repository in your AWS account, and selects the correct one. 

				
					aws codecommit create-repository --repository-name demo-sam-app --profile abhi
				
			

You should see the output similar to the following:

				
					{
    "repositoryMetadata": {
        "accountId": "XXXXXXXXXXXX",
        "repositoryId": "20b2bb39-8dba-4cce-89a3-604e91e9dcc4",
        "repositoryName": "demo-sam-app",
        "lastModifiedDate": "2022-07-04T13:16:26.682000+12:00",
        "creationDate": "2022-07-04T13:16:26.682000+12:00",
        "cloneUrlHttp": "https://git-codecommit.ap-southeast-2.amazonaws.com/v1/repos/demo-sam-app",
        "cloneUrlSsh": "ssh://git-codecommit.ap-southeast-2.amazonaws.com/v1/repos/demo-sam-app",
        "Arn": "arn:aws:codecommit:ap-southeast-2:XXXXXXXXXXXX:demo-sam-app"
    }
}
				
			

Step 2: Configure CodeCommit Credentials

Refer to the AWS documentation for authentication and access control for AWS CodeCommit. For this demo, we will use our existing AWS IAM user, which you have configured for AWS CLI access, and create HTTPS git credentials to access the AWS CodeCommit git repository.

Sign in to AWS Management Console, and open the IAM console; in the navigation pane, choose Users and go to the Security Credentials tab and Generate the HTTPS git Credentials.

Download the credentials; you need them in the next step.

Step 3: Clone the CodeCommit git Repository

Grab the HTTPS endpoint from the CodeCommit Console.

Clone the empty git repository. Provide the Username and Password we have saved in the previous step—change the directory to demo-sam-app and checkout the git “main” branch.

				
					git clone https://git-codecommit.ap-southeast-2.amazonaws.com/v1/repos/demo-sam-app
Cloning into 'demo-sam-app'...
Username for 'https://git-codecommit.ap-southeast-2.amazonaws.com': abhi-at-XXXXXXXXXXXX
Password for 'https://abhi-at-XXXXXXXXXXXX@git-codecommit.ap-southeast-2.amazonaws.com':
warning: You appear to have cloned an empty repository.

cd demo-sam-app/

git checkout -b main
				
			

Step 4: Initialize the SAM Application

AWS SAM provides you with a command line tool, the AWS SAM CLI, that makes it easy for you to create and manage serverless applications. It particularly makes easy the scaffolding of a new project, as it creates the initial skeleton of a hello world application, so you can use it as a baseline and continue building your project from there.

				
					sam init

You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.

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
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Infrastructure event management
        8 - Machine Learning
Template: 1

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

Which runtime would you like to use?
        1 - dotnet6
        2 - dotnet5.0
        3 - dotnetcore3.1
        4 - go1.x
        5 - graalvm.java11 (provided.al2)
        6 - graalvm.java17 (provided.al2)
        7 - java11
        8 - java8.al2
        9 - java8
        10 - nodejs16.x
        11 - nodejs14.x
        12 - nodejs12.x
        13 - python3.9
        14 - python3.8
        15 - python3.7
        16 - python3.6
        17 - ruby2.7
        18 - rust (provided.al2)
Runtime: 15

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

Based on your selections, the only dependency manager available is pip.
We will proceed copying the template using pip.

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

Project name [sam-app]: demo-sam-app

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: demo-sam-app
    Runtime: python3.7
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .

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


    Commands you can use next
    =========================
    [*] Create pipeline: cd demo-sam-app && sam pipeline init --bootstrap
    [*] Validate SAM template: sam validate
    [*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch
				
			

Step 5: Creating the SAM Pipeline

There are three distinct steps with SAM pipelines and AWS CodePipeline.

  • Create required IAM roles and infrastructure
  • Create a CloudFormation pipeline template
  • Deploy CloudFormation pipeline template

SAM Pipelines automates all of this for us. The “sam pipeline init –bootstrap” command will guide you through a long series of questions.

				
					cd demo-sam-app/
sam pipeline init --bootstrap
				
			
Stage 1 – Dev Stage
				
					sam pipeline init generates a pipeline configuration file that your CI/CD system
can use to deploy serverless applications using AWS SAM.
We will guide you through the process to bootstrap resources for each stage,
then walk through the details necessary for creating the pipeline config file.

Please ensure you are in the root folder of your SAM application before you begin.

Select a pipeline template to get started:
        1 - AWS Quick Start Pipeline Templates
        2 - Custom Pipeline Template Location
Choice: 1

Cloning from https://github.com/aws/aws-sam-cli-pipeline-init-templates.git (process may take a moment)
Select CI/CD system
        1 - Jenkins
        2 - GitLab CI/CD
        3 - GitHub Actions
        4 - Bitbucket Pipelines
        5 - AWS CodePipeline
Choice: 5
You are using the 2-stage pipeline template.
 _________    _________
|         |  |         |
| Stage 1 |->| Stage 2 |
|_________|  |_________|

Checking for existing stages...

[!] None detected in this account.

Do you want to go through stage setup process now? If you choose no, you can still reference other bootstrapped resources. [y/N]: y

For each stage, we will ask for [1] stage definition, [2] account details, and [3]
reference application build resources in order to bootstrap these pipeline
resources.

We recommend using an individual AWS account profiles for each stage in your
pipeline. You can set these profiles up using aws configure or ~/.aws/credentials. See
[https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-set-up-credentials.html].


Stage 1 Setup

[1] Stage definition
Enter a configuration name for this stage. This will be referenced later when you use the sam pipeline init command:
Stage configuration name: dev

[2] Account details
The following AWS credential sources are available to use.
To know more about configuration AWS credentials, visit the link below:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
        1 - Environment variables (not available)
        2 - default (named profile)
        3 - ltc (named profile)
        4 - abhi (named profile)
        q - Quit and configure AWS credentials
Select a credential source to associate with this stage: 4
Associated account XXXXXXXXXXXX with configuration dev.

Enter the region in which you want these resources to be created [ap-southeast-2]:
Enter the pipeline IAM user ARN if you have previously created one, or we will create one for you []:

[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]: N

[4] Summary
Below is the summary of the answers:
        1 - Account: XXXXXXXXXXXX
        2 - Stage configuration name: dev
        3 - Region: ap-southeast-2
        4 - Pipeline user: [to be created]
        5 - Pipeline execution role: [to be created]
        6 - CloudFormation execution role: [to be created]
        7 - Artifacts bucket: [to be created]
        8 - 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:
        - Pipeline IAM user
        - Pipeline execution role
        - CloudFormation execution role
        - Artifact bucket
Should we proceed with the creation? [y/N]: y
        Creating the required resources...
        Successfully created!
The following resources were created in your account:
        - Pipeline IAM user
        - Pipeline execution role
        - CloudFormation execution role
        - Artifact bucket
Pipeline IAM user credential:
        AWS_ACCESS_KEY_ID: XXXXXXXXXXXXXXXXXXXX
        AWS_SECRET_ACCESS_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
View the definition in .aws-sam/pipeline/pipelineconfig.toml,
run sam pipeline bootstrap to generate another set of resources, or proceed to
sam pipeline init to create your pipeline configuration file.
				
			
				
					Before running sam pipeline init, we recommend first setting up AWS credentials
in your CI/CD account. Read more about how to do so with your provider in
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-generating-example-ci-cd-others.html.

Checking for existing stages...

Only 1 stage(s) were detected, fewer than what the template requires: 2.

Do you want to go through stage setup process now? If you choose no, you can still reference other bootstrapped resources. [y/N]: y

For each stage, we will ask for [1] stage definition, [2] account details, and [3]
reference application build resources in order to bootstrap these pipeline
resources.

We recommend using an individual AWS account profiles for each stage in your
pipeline. You can set these profiles up using aws configure or ~/.aws/credentials. See
[https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-set-up-credentials.html].


				
			
Stage 2 – Prod Stage

SAM Pipelines detects that a second stage is required and prompts you to go through the set-up process for this new stage. Since you have created the necessary resource for the dev build stage, you need to go through the same steps for a prod stage. You will see output that looks like the following.

Most questions can be answered as in the dev stage created above. The one change you need to make is the first question which is the “Stage configuration, name,” which should be prod. Also, note the default value for the “Pipeline IAM user ARN” (question 4) prompt will be filled in. This is the ARN for the Pipeline user created during the dev stage above.

				
					Stage 2 Setup

[1] Stage definition
Enter a configuration name for this stage. This will be referenced later when you use the sam pipeline init command:
Stage configuration name: prod

[2] Account details
The following AWS credential sources are available to use.
To know more about configuration AWS credentials, visit the link below:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
        1 - Environment variables (not available)
        2 - default (named profile)
        3 - ltc (named profile)
        4 - abhi (named profile)
        q - Quit and configure AWS credentials
Select a credential source to associate with this stage: 4
Associated account XXXXXXXXXXXX with configuration prod.

Enter the region in which you want these resources to be created [ap-southeast-2]:
Pipeline IAM user ARN: arn:aws:iam::XXXXXXXXXXXX:user/aws-sam-cli-managed-dev-pipeline-reso-PipelineUser-13K4HTJJDXAM7

[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]: N

[4] Summary
Below is the summary of the answers:
        1 - Account: XXXXXXXXXXXX
        2 - Stage configuration name: prod
        3 - Region: ap-southeast-2
        4 - Pipeline user ARN: arn:aws:iam::XXXXXXXXXXXX:user/aws-sam-cli-managed-dev-pipeline-reso-PipelineUser-13K4HTJJDXAM7
        5 - Pipeline execution role: [to be created]
        6 - CloudFormation execution role: [to be created]
        7 - Artifacts bucket: [to be created]
        8 - 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 'prod' configuration:
        - Pipeline execution role
        - CloudFormation execution role
        - Artifact bucket
Should we proceed with the creation? [y/N]: y
        Creating the required resources...
        Successfully created!
The following resources were created in your account:
        - Pipeline execution role
        - CloudFormation execution role
        - Artifact bucket
View the definition in .aws-sam/pipeline/pipelineconfig.toml,
run sam pipeline bootstrap to generate another set of resources, or proceed to
sam pipeline init to create your pipeline configuration file.
				
			

These resources were created with a CloudFormation stack that SAM Pipelines synthesized and launched. You may optionally navigate to the CloudFormation console and inspect this stack to see everything that was created.

In this step, SAM pipelines created a Pipeline IAM user with an associated ACCESS_KEY_ID and SECRET_ACCESS_KEY, shown in the output. The CodePipeline we will eventually create uses this user to deploy artifacts to your AWS accounts. This IAM user will be the default value in subsequent steps.

Create CloudFormation pipeline template

Now that AWS SAM has created supporting resources we’ll continue to create a CloudFormation template that will define our entire CI/CD pipeline.

				
					Checking for existing stages...

What is the Git provider?
        1 - Bitbucket
        2 - CodeCommit
        3 - GitHub
        4 - GitHubEnterpriseServer
Choice []: 2
What is the CodeCommit repository name?: demo-sam-app
What is the Git branch used for production deployments? [main]:
What is the template file path? [template.yaml]:
We use the stage configuration name to automatically retrieve the bootstrapped resources created when you ran `sam pipeline bootstrap`.

Here are the stage configuration names detected in .aws-sam/pipeline/pipelineconfig.toml:
        1 - dev
        2 - prod
Select an index or enter the stage 1's configuration name (as provided during the bootstrapping): 1
What is the sam application stack name for stage 1? [sam-app]: sam-app-dev
Stage 1 configured successfully, configuring stage 2.

Here are the stage configuration names detected in .aws-sam/pipeline/pipelineconfig.toml:
        1 - dev
        2 - prod
Select an index or enter the stage 2's configuration name (as provided during the bootstrapping): 2
What is the sam application stack name for stage 2? [sam-app]: sam-app-prod
Stage 2 configured successfully.

To deploy this template and connect to the main git branch, run this against the leading account:
`sam deploy -t codepipeline.yaml --stack-name <stack-name> --capabilities=CAPABILITY_IAM`.
SUMMARY
We will generate a pipeline config file based on the following information:
        What is the Git provider?: CodeCommit
        What is the CodeCommit repository name?: demo-sam-app
        What is the Git branch used for production deployments?: main
        What is the template file path?: template.yaml
        Select an index or enter the stage 1's configuration name (as provided during the bootstrapping): 1
        What is the sam application stack name for stage 1?: sam-app-dev
        What is the pipeline execution role ARN for stage 1?: arn:aws:iam::930935953797:role/aws-sam-cli-managed-dev-pipe-PipelineExecutionRole-1VYNZBDCGJ8H1
        What is the CloudFormation execution role ARN for stage 1?: arn:aws:iam::XXXXXXXXXXXX:role/aws-sam-cli-managed-dev-p-CloudFormationExecutionR-1WFZ62IDMG4BW
        What is the S3 bucket name for artifacts for stage 1?: aws-sam-cli-managed-dev-pipeline-artifactsbucket-1lrs2pusw4l42
        What is the ECR repository URI for stage 1?:
        What is the AWS region for stage 1?: ap-southeast-2
        Select an index or enter the stage 2's configuration name (as provided during the bootstrapping): 2
        What is the sam application stack name for stage 2?: sam-app-prod
        What is the pipeline execution role ARN for stage 2?: arn:aws:iam::XXXXXXXXXXXX:role/aws-sam-cli-managed-prod-pip-PipelineExecutionRole-13F3G3IPKKGP5
        What is the CloudFormation execution role ARN for stage 2?: arn:aws:iam::XXXXXXXXXXXX:role/aws-sam-cli-managed-prod-CloudFormationExecutionR-ZAAJ3JLXDIR6
        What is the S3 bucket name for artifacts for stage 2?: aws-sam-cli-managed-prod-pipeline-artifactsbucket-1t0hjy7nashbl
        What is the ECR repository URI for stage 2?:
        What is the AWS region for stage 2?: ap-southeast-2
Successfully created the pipeline configuration file(s):
        - assume-role.sh
        - codepipeline.yaml
        - pipeline/buildspec_build_package.yml
        - pipeline/buildspec_deploy.yml
        - pipeline/buildspec_feature.yml
        - pipeline/buildspec_integration_test.yml
        - pipeline/buildspec_unit_test.yml
				
			

We’ve just created the CloudFormation template and supporting configuration files to create a complete CI/CD Pipeline using AWS CodePipeline, CodeBuild, and other AWS services.

Your project should have the structure below.

				
					tree demo-sam-app

demo-sam-app
├── README.md
├── __init__.py
├── assume-role.sh
├── codepipeline.yaml 
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── pipeline
│   ├── buildspec_build_package.yml
│   ├── buildspec_deploy.yml
│   ├── buildspec_feature.yml
│   ├── buildspec_integration_test.yml
│   └── buildspec_unit_test.yml
├── template.yaml
└── tests
    ├── __init__.py
    └── unit
        ├── __init__.py
        └── test_handler.py
				
			

You can optionally open up the codepipeline.yaml and other files to see what SAM Pipelines created for us—looking at codepipeline.yaml, you can see that there are nearly 700 lines of CloudFormation that SAM created. Think about how much time you saved using SAM Pipelines rather than crafting this by hand!

Note: We haven’t created any CI/CD systems just yet! You’ll do that next. First, you must commit your CI/CD configuration files into your repository. Once that’s done, you can create your CodePipeline with CloudFormation, via SAM.

Step 6: Deploy CloudFormation pipeline template

We need to add the new CI/CD configuration files to our repository.

 

				
					git status

On branch master
No commits yet
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .aws-sam/
        README.md
        __init__.py
        assume-role.sh
        codepipeline.yaml
        events/
        hello_world/
        pipeline/
        template.yaml
        tests/
				
			

In the terminal, run the following commands from the root directory of your demo-sam-app project.

				
					git add .

git commit -m "Adding SAM CI/CD Pipeline definition"
[master (root-commit) 9b5dfdf] Adding SAM CI/CD Pipeline definition
 18 files changed, 1162 insertions(+)
 create mode 100644 .aws-sam/pipeline/pipelineconfig.toml
 create mode 100644 README.md
 create mode 100644 __init__.py
 create mode 100755 assume-role.sh
 create mode 100644 codepipeline.yaml
 create mode 100644 events/event.json
 create mode 100644 hello_world/__init__.py
 create mode 100644 hello_world/app.py
 create mode 100644 hello_world/requirements.txt
 create mode 100644 pipeline/buildspec_build_package.yml
 create mode 100644 pipeline/buildspec_deploy.yml
 create mode 100644 pipeline/buildspec_feature.yml
 create mode 100644 pipeline/buildspec_integration_test.yml
 create mode 100644 pipeline/buildspec_unit_test.yml
 create mode 100644 template.yaml
 create mode 100644 tests/__init__.py
 create mode 100644 tests/unit/__init__.py
 create mode 100644 tests/unit/test_handler.py

git push
Username for 'https://git-codecommit.ap-southeast-2.amazonaws.com': abhi-at-930935953797
Password for 'https://abhi-at-930935953797@git-codecommit.ap-southeast-2.amazonaws.com':
Enumerating objects: 24, done.
Counting objects: 100% (24/24), done.
Delta compression using up to 8 threads
Compressing objects: 100% (19/19), done.
Writing objects: 100% (24/24), 12.86 KiB | 1.61 MiB/s, done.
Total 24 (delta 3), reused 0 (delta 0)
To https://git-codecommit.ap-southeast-2.amazonaws.com/v1/repos/demo-sam-app
 * [new branch]      master -> master

				
			

Now that configuration is checked into source control, you can create a new CloudFormation stack to set up our CI/CD pipeline. You will use the "sam deploy" command to launch this new stack. It’s important to recognize that you’re using SAM’s ability to launch arbitrary CloudFormation templates. SAM isn’t building or deploying your serverless application here but instead launching the codepipeline.yaml CI/CD template.

				
					sam deploy -t codepipeline.yaml --stack-name sam-app-pipeline --capabilities=CAPABILITY_IAM



        Deploying with following values
        ===============================
        Stack name                   : sam-app-pipeline
        Region                       : None
        Confirm changeset            : False
        Disable rollback             : False
        Deployment s3 bucket         : None
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

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

Waiting for changeset to be created..
CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                  LogicalResourceId                          ResourceType                               Replacement
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                      CloudWatchEventRole                        AWS::IAM::Role                             N/A
+ Add                                      CloudWatchEventRule                        AWS::Events::Rule                          N/A
+ Add                                      CodeBuildProjectBuildAndPackage            AWS::CodeBuild::Project                    N/A
+ Add                                      CodeBuildProjectDeploy                     AWS::CodeBuild::Project                    N/A
+ Add                                      CodeBuildServiceRole                       AWS::IAM::Role                             N/A
+ Add                                      CodePipelineExecutionRole                  AWS::IAM::Role                             N/A
+ Add                                      PipelineArtifactsBucketPolicy              AWS::S3::BucketPolicy                      N/A
+ Add                                      PipelineArtifactsBucket                    AWS::S3::Bucket                            N/A
+ Add                                      PipelineArtifactsLoggingBucketPolicy       AWS::S3::BucketPolicy                      N/A
+ Add                                      PipelineArtifactsLoggingBucket             AWS::S3::Bucket                            N/A
+ Add                                      PipelineStackCloudFormationExecutionRole   AWS::IAM::Role                             N/A
+ Add                                      Pipeline                                   AWS::CodePipeline::Pipeline                N/A
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-southeast-2:930935953797:changeSet/samcli-deploy1656936021/5e7b1c3e-3783-4273-934f-a018c9f0e42f


2022-07-05 00:00:28 - 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::IAM::Role                             PipelineStackCloudFormationExecutionRole   -
CREATE_IN_PROGRESS                         AWS::S3::Bucket                            PipelineArtifactsLoggingBucket             -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             PipelineStackCloudFormationExecutionRole   Resource creation Initiated
CREATE_IN_PROGRESS                         AWS::S3::Bucket                            PipelineArtifactsLoggingBucket             Resource creation Initiated
CREATE_COMPLETE                            AWS::S3::Bucket                            PipelineArtifactsLoggingBucket             -
CREATE_IN_PROGRESS                         AWS::S3::BucketPolicy                      PipelineArtifactsLoggingBucketPolicy       -
CREATE_IN_PROGRESS                         AWS::S3::Bucket                            PipelineArtifactsBucket                    -
CREATE_IN_PROGRESS                         AWS::S3::BucketPolicy                      PipelineArtifactsLoggingBucketPolicy       Resource creation Initiated
CREATE_COMPLETE                            AWS::S3::BucketPolicy                      PipelineArtifactsLoggingBucketPolicy       -
CREATE_IN_PROGRESS                         AWS::S3::Bucket                            PipelineArtifactsBucket                    Resource creation Initiated
CREATE_COMPLETE                            AWS::IAM::Role                             PipelineStackCloudFormationExecutionRole   -
CREATE_COMPLETE                            AWS::S3::Bucket                            PipelineArtifactsBucket                    -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CodeBuildServiceRole                       -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CodeBuildServiceRole                       Resource creation Initiated
CREATE_COMPLETE                            AWS::IAM::Role                             CodeBuildServiceRole                       -
CREATE_IN_PROGRESS                         AWS::CodeBuild::Project                    CodeBuildProjectDeploy                     -
CREATE_IN_PROGRESS                         AWS::CodeBuild::Project                    CodeBuildProjectBuildAndPackage            -
CREATE_IN_PROGRESS                         AWS::CodeBuild::Project                    CodeBuildProjectBuildAndPackage            Resource creation Initiated
CREATE_IN_PROGRESS                         AWS::CodeBuild::Project                    CodeBuildProjectDeploy                     Resource creation Initiated
CREATE_COMPLETE                            AWS::CodeBuild::Project                    CodeBuildProjectBuildAndPackage            -
CREATE_COMPLETE                            AWS::CodeBuild::Project                    CodeBuildProjectDeploy                     -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CodePipelineExecutionRole                  -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CodePipelineExecutionRole                  Resource creation Initiated
CREATE_COMPLETE                            AWS::IAM::Role                             CodePipelineExecutionRole                  -
CREATE_IN_PROGRESS                         AWS::S3::BucketPolicy                      PipelineArtifactsBucketPolicy              -
CREATE_IN_PROGRESS                         AWS::S3::BucketPolicy                      PipelineArtifactsBucketPolicy              Resource creation Initiated
CREATE_COMPLETE                            AWS::S3::BucketPolicy                      PipelineArtifactsBucketPolicy              -
CREATE_IN_PROGRESS                         AWS::CodePipeline::Pipeline                Pipeline                                   -
CREATE_IN_PROGRESS                         AWS::CodePipeline::Pipeline                Pipeline                                   Resource creation Initiated
CREATE_COMPLETE                            AWS::CodePipeline::Pipeline                Pipeline                                   -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CloudWatchEventRole                        -
CREATE_IN_PROGRESS                         AWS::IAM::Role                             CloudWatchEventRole                        Resource creation Initiated
CREATE_COMPLETE                            AWS::IAM::Role                             CloudWatchEventRole                        -
CREATE_IN_PROGRESS                         AWS::Events::Rule                          CloudWatchEventRule                        -
CREATE_IN_PROGRESS                         AWS::Events::Rule                          CloudWatchEventRule                        Resource creation Initiated
CREATE_COMPLETE                            AWS::Events::Rule                          CloudWatchEventRule                        -
CREATE_COMPLETE                            AWS::CloudFormation::Stack                 sam-app-pipeline                           -
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - sam-app-pipeline in None
				
			

This will take a few minutes to complete, so be patient! You can optionally open the CloudFormation console to watch the progress of this new stack. Eventually, the stack will complete, and you can see the final AWS resources it created.

Step 7: Inspect the pipeline

Once the sam-app-pipeline CloudFormation stack has been completed, you will have a new CodePipeline Pipeline. Navigate to the CodePipeline Console. You should see a single Pipeline. If you’ve navigated here soon after deploying the pipeline CloudFormation stack, you will see your new Pipeline executing its first deployment.

Let your pipeline run every stage. After it finishes all stages will be green.

You can find Dev and Prod endpoint Information in CloudFormation Console.

 

Look at the Outputs tab for each of these CloudFormation stacks to see the API endpoints. You can use curl or other methods to verify the functionality of your two new APIs. You can export the URL endpoints for both stages in a terminal.

				
					export DEV_ENDPOINT=$(aws cloudformation describe-stacks --stack-name sam-app-dev --profile abhi | jq -r '.Stacks[].Outputs[].OutputValue | select(startswith("https://"))')
export PROD_ENDPOINT=$(aws cloudformation describe-stacks --stack-name sam-app-prod --profile abhi | jq -r '.Stacks[].Outputs[].OutputValue | select(startswith("https://"))')

echo "Dev endpoint: $DEV_ENDPOINT"
Dev endpoint: https://i64bsc8xm4.execute-api.ap-southeast-2.amazonaws.com/Prod/hello/

echo "Prod endpoint: $PROD_ENDPOINT"
Prod endpoint: https://lixaoribvc.execute-api.ap-southeast-2.amazonaws.com/Prod/hello/

curl -s $DEV_ENDPOINT
{"message": "hello world"}

curl -s $PROD_ENDPOINT
{"message": "hello world"}
				
			

Conclusion

AWS SAM Pipelines help automate applications’ build and deployment process by leveraging AWS CodeBuild, AWS CodeCommit, AWS CodeDeploy, and AWS CodePipeline. With SAM Pipelines, organizations can leverage templates to help standardize pipeline resources and accelerate deployments by orchestrating provisioning and configuration steps.

(Visited 585 times, 1 visits today)