DEVELOPER BLOG

HOME > DEVELOPER BLOG > 【Introduction to AWS】Building Serverless Applications with AWS SAM CLI - PrismScaler

【Introduction to AWS】Building Serverless Applications with AWS SAM CLI - PrismScaler

1. Introduction

Hello! We are a writer team from Definer Inc. AWS SAM (Serverless Application Model) is a powerful framework for building serverless applications on AWS. It extends AWS CloudFormation to provide an easy and efficient way to define and deploy serverless resources, including AWS Lambda functions, Amazon API Gateway endpoints, and Amazon DynamoDB tables. AWS SAM CLI (Command Line Interface) is a command-line tool that complements AWS SAM, enabling developers to build, test, and deploy serverless applications locally and in the cloud. In this issue, you are wondering how to build a serverless application using AWS SAM CLI. Let's take a look at the actual screens and resources to explain in detail.

2. Purpose/Use Cases

The purpose of building serverless applications with AWS SAM CLI is to streamline the development and deployment process for serverless applications on AWS. AWS SAM CLI simplifies the workflow, allowing developers to focus on writing code and building application logic, while it takes care of the complexities of creating and configuring serverless resources. Key Objectives of Building Serverless Applications with AWS SAM CLI: (1) Local Development and Testing (2) Create and Manage AWS Resources (3) Support for Multiple Runtimes (4) Local API Testing (5) Lambda Function Debugging (6) Deployment to AWS (7) Infrastructure as Code (IaC) Practices

3. What is AWS SAM?

AWS SAM (Serverless Application Model) is an open-source framework provided by Amazon Web Services (AWS) to simplify the development and deployment of serverless applications on AWS Cloud. It extends AWS CloudFormation, which is AWS's infrastructure as code service, to define and deploy serverless resources like AWS Lambda functions, Amazon API Gateway endpoints, Amazon DynamoDB tables, and Amazon S3 buckets in a more concise and efficient manner. The primary goal of AWS SAM is to streamline the process of building serverless applications by abstracting away the complexity of resource provisioning and configuration. With AWS SAM, developers can define serverless applications using a simple and intuitive YAML or JSON template syntax, allowing them to focus on writing application code and business logic rather than dealing with infrastructure management. Key features and components of AWS SAM include:  - Template Syntax  - Lambda Functions  - API Gateway Integration  - Local Development and Testing  - Reusable Code  - Deployment and Updates  - Versioning and Rollback  - Integration with AWS Services

4. Setup of AWS SAM CLI

To start building a serverless application using the AWS SAM CLI, you will first need to set up the AWS SAM CLI on your development environment. If you are using AWS Cloud9, the AWS SAM CLI is typically pre-installed. Here are the steps to build a serverless application: (1) Initial Setup of AWS SAM CLI: Use the "sam init" command to perform the initial setup of your serverless application. You can choose from various AWS Quick Start Templates to scaffold your project. For example, you might select the "Hello World Example" template. After running "sam init," you will see that various files and directories are created in your project directory. These files include "template.yaml" (the SAM template file), Lambda function code files, and other configuration files. (2) Align Python Versions: In some cases, there might be a mismatch between the Python version specified in your "template.yaml" file and the version installed on your development environment. To address this, ensure that the Python version specified in "template.yaml" matches the Python version installed on your system. For example, if the Python version on your OS is 3.7 but the version specified in "template.yaml" is 3.9, you should update the "runtime" attribute in "template.yaml" to use Python 3.7. Once you have completed these initial setup steps, you can start developing your serverless application. The "template.yaml" file serves as the SAM template, where you define your AWS resources, including Lambda functions, APIs, event triggers, and more. You can write your Lambda function code in the respective function code files created during the initial setup. After writing your application code, you can use the AWS SAM CLI to test your application locally by running "sam local invoke" or "sam local start-api" commands, depending on your use case. This allows you to validate the behavior of your serverless functions and API endpoints before deploying to AWS. Finally, when you are ready to deploy your serverless application to AWS, you can use the "sam deploy" command. This command packages and uploads your application code and SAM template to AWS CloudFormation, which then creates the specified AWS resources in your AWS account. This enables you to run and manage your serverless application at scale on the AWS Cloud.
## Check SAM CLI version
USERNAME:~/environment $ sam --version
SAM CLI, version 1.57.0


## Initial SAM settings
USERNAME:~/environment $ sam init

        SAM CLI now collects telemetry to better understand customer needs.

        You can OPT OUT and disable telemetry collection by setting the
        environment variable SAM_CLI_TELEMETRY=0 in your shell.
        Thanks for your help!

        Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html


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 - Lambda EFS example
        9 - Machine Learning
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]: N

Project name [sam-app]: sam-test

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

    -----------------------
    Generating application:
    -----------------------
    Name: sam-test
    Runtime: python3.9
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    
    Next steps can be found in the README file at ./sam-test/README.md
        

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

SAM CLI update available (1.61.0); (1.57.0 installed)
To download: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html


## Initial setup complete
## A directory named sam-test is created.
USERNAME:~/environment $ ls
README.md  sam-test
USERNAME:~/environment $ cd sam-test/
USERNAME:~/environment/sam-test $ ls
events  hello_world  __init__.py  README.md  template.yaml  tests                
## The version of python is 3.7
USERNAME:~/environment $ python --version
Python 3.7.10


## Python version in template.yaml file is 3.9
USERNAME:~/environment/sam-test $ cat template.yaml 
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-test

  Sample SAM Template for sam-test

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

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
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn


## Correct python version of template.yaml 3.9 -> 3.7
USERNAME:~/environment $ vim template.yaml                  

5. Building serverless applications using AWS SAM

Congratulations on building your serverless application using the AWS SAM CLI! Let's dive deeper into the steps you took for building and deploying the application: (1) Build: The "sam build" command is used to build your serverless application. During this step, AWS SAM CLI automatically identifies the necessary dependencies, packages, and builds your Lambda functions and other resources based on the SAM template ("template.yaml") in your project directory. It ensures that all required assets are prepared for deployment. (2) Local Execution: After the build process, you executed the application locally using the "sam local invoke" command. This command allows you to test your Lambda functions locally without the need to deploy them to AWS. In your case, the test was successful, and the Lambda function executed correctly, displaying "Hello World." (3) Deployment: The final step involved deploying your serverless application to AWS using the "sam deploy --guided" command. This command initiates the deployment process through AWS CloudFormation, AWS's infrastructure management service. The "--guided" option prompts you to provide configuration details interactively, such as the AWS region, stack name, and any parameters defined in your SAM template. After the successful deployment, you can access the AWS Management Console, specifically the CloudFormation and Lambda services, to view the CloudFormation stack and the Lambda function that were created. The CloudFormation stack represents the collection of AWS resources that make up your serverless application, and it helps manage the entire lifecycle of those resources. The AWS SAM CLI provides a streamlined workflow for building and deploying serverless applications on AWS. By abstracting away the complexities of infrastructure provisioning and resource management, it enables developers to focus on writing application logic and rapidly iterate on their code. The local execution capability allows for fast and efficient testing before deploying to the cloud, reducing development time and minimizing the risk of issues in production.
## build
USERNAME:~/environment/sam-test $ sam build
Your template contains a resource with logical ID "ServerlessRestApi", which is a reserved logical ID in AWS SAM. It could result in unexpected behaviors and is not recommended.
Building codeuri: /home/ec2-user/environment/sam-test/hello_world runtime: python3.7 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

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


## local run
USERNAME:~/environment/sam-test $ sam local invoke
Invoking app.lambda_handler (python3.7)
Image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-python3.7
Building image..........................................................................................................................................................................................................................................................................................................
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.7:rapid-1.57.0-x86_64.

Mounting /home/ec2-user/environment/sam-test/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
END RequestId: XXXXXXXXXXX
REPORT RequestId: XXXXXXXXXXXXX  Init Duration: 0.73 ms  Duration: 105.84 ms     Billed Duration: 106 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}                
## deploy
USERNAME:~/environment/sam-test $ sam deploy --guided

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

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: sam-test
        AWS Region [ap-northeast-1]: 
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: y
        #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]: Y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: y
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: Y
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: 

        Looking for resources needed for deployment:
        Creating the required resources...
        Successfully created!
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-Xxxxxxxx
         A different default S3 bucket can be set in 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-test/1007baxxxxxxx92f298d  466367 / 466367  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : sam-test
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : True
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-1clbxxxxxqdk
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
Uploading to sam-test/3b61a95a683xxxxxxxxxd6.template  1183 / 1183  (100.00%)

Waiting for changeset to be created..
CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                              LogicalResourceId                                      ResourceType                                           Replacement                                          
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                                  HelloWorldFunctionHelloWorldPermissionProd             AWS::Lambda::Permission                                N/A                                                  
+ Add                                                  HelloWorldFunctionRole                                 AWS::IAM::Role                                         N/A                                                  
+ Add                                                  HelloWorldFunction                                     AWS::Lambda::Function                                  N/A                                                  
+ Add                                                  ServerlessRestApiDeployment47fc2d5f9d                  AWS::ApiGateway::Deployment                            N/A                                                  
+ Add                                                  ServerlessRestApiProdStage                             AWS::ApiGateway::Stage                                 N/A                                                  
+ Add                                                  ServerlessRestApi                                      AWS::ApiGateway::RestApi                               N/A                                                  
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxx:changeSet/samcli-deploy166xxxxx05/08xxxxxxxxxfa-9c97177f9a11


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

2022-11-01 03:05:31 - 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                                         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::RestApi                               ServerlessRestApi                                      -                                                    
CREATE_IN_PROGRESS                                     AWS::ApiGateway::RestApi                               ServerlessRestApi                                      Resource creation Initiated                          
CREATE_COMPLETE                                        AWS::ApiGateway::RestApi                               ServerlessRestApi                                      -                                                    
CREATE_IN_PROGRESS                                     AWS::ApiGateway::Deployment                            ServerlessRestApiDeployment47fc2d5f9d                  -                                                    
CREATE_IN_PROGRESS                                     AWS::Lambda::Permission                                HelloWorldFunctionHelloWorldPermissionProd             -                                                    
CREATE_IN_PROGRESS                                     AWS::Lambda::Permission                                HelloWorldFunctionHelloWorldPermissionProd             Resource creation Initiated                          
CREATE_IN_PROGRESS                                     AWS::ApiGateway::Deployment                            ServerlessRestApiDeployment47fc2d5f9d                  Resource creation Initiated                          
CREATE_COMPLETE                                        AWS::ApiGateway::Deployment                            ServerlessRestApiDeployment47fc2d5f9d                  -                                                    
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                                HelloWorldFunctionHelloWorldPermissionProd             -                                                    
CREATE_COMPLETE                                        AWS::CloudFormation::Stack                             sam-test                                               -                                                    
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                                             
Description         Implicit IAM Role created for Hello World function                                                                                                                                                    
Value               arn:aws:iam::xxxxxxxxx:role/sam-test-HelloWorldFunctionRole-U4PFODQMD3N8                                                                                                                           

Key                 HelloWorldApi                                                                                                                                                                                         
Description         API Gateway endpoint URL for Prod stage for Hello World function                                                                                                                                      
Value               https://2xxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/                                                                                                                               

Key                 HelloWorldFunction                                                                                                                                                                                    
Description         Hello World Lambda Function ARN                                                                                                                                                                       
Value               arn:aws:lambda:ap-northeast-1:xxxxxxxxx:function:sam-test-HelloWorldFunction-jwLlJxxxxxxx                                                                                                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - sam-test in ap-northeast-1                  

6. Cited/Referenced Articles

7. About the proprietary solution "PrismScaler"

・PrismScaler is a web service that enables the construction of multi-cloud infrastructures such as AWS, Azure, and GCP in just three steps, without requiring development and operation. ・PrismScaler is a web service that enables multi-cloud infrastructure construction such as AWS, Azure, GCP, etc. in just 3 steps without development and operation. ・The solution is designed for a wide range of usage scenarios such as cloud infrastructure construction/cloud migration, cloud maintenance and operation, and cost optimization, and can easily realize more than several hundred high-quality general-purpose cloud infrastructures by appropriately combining IaaS and PaaS.  

8. Contact us

This article provides useful introductory information free of charge. For consultation and inquiries, please contact "Definer Inc".

9. Regarding Definer

・Definer Inc. provides one-stop solutions from upstream to downstream of IT. ・We are committed to providing integrated support for advanced IT technologies such as AI and cloud IT infrastructure, from consulting to requirement definition/design development/implementation, and maintenance and operation. ・We are committed to providing integrated support for advanced IT technologies such as AI and cloud IT infrastructure, from consulting to requirement definition, design development, implementation, maintenance, and operation. ・PrismScaler is a high-quality, rapid, "auto-configuration," "auto-monitoring," "problem detection," and "configuration visualization" for multi-cloud/IT infrastructure such as AWS, Azure, and GCP.