Benefits of Using AWS SAM: Unlock the Power of Serverless Computing

Tue Jan 31 2023Yogesh Bisht

AWS SAM is a framework for creating serverless applications on AWS. It allows developers to define their application’s resources, such as functions and databases, using a simple template file.

Benefits of Using AWS SAM:  Unlock the Power of Serverless Computing

Are you looking for a powerful yet easy-to-use serverless computing platform? If yes, then AWS SAM (Serverless Application Model) is the perfect solution for you. AWS SAM provides developers with an intuitive and easy-to-use platform for creating, deploying, and managing serverless applications. 


In this blog, we’ll explore the benefits of using AWS SAM and how it can help you unlock the power of serverless computing.


What is AWS Sam?


AWS SAM is a framework for creating serverless applications on AWS. It allows developers to define their application’s resources using a simple template file, such as functions and databases. The template file can then deploy the application on AWS with a few clicks. 


Some benefits of using AWS SAM:


  • Simplified Deployment
  • Better Resource Management
  • Improved Monitoring and Debugging
  • Cost Optimization
  • Increased Productivity


Overall, AWS SAM is a powerful tool for unlocking the full potential of serverless computing. Now I think we have seen Serverless Application Model's theoretical concept. Let's go through some code shit and dive into it.


Setup SAM on Desktop:-


To set up SAM on your desktop you must have AWS CLI configured. If not I would suggest going through this documentation. Once you are done with that Install a compatible SAM version for your machine from AWS documentation.


Create Your First SAM Project:-


Note:- Either you can use the SAM init and follow the terminal option to create your project or you can follow along with me where I will demonstrate building a production-ready SAM project from scratch.


following is a high-level view of the serverless application that we are going to build.


serverless application model high level design


Now follow the below steps to build the serverless application and unlock the power of serverless computing.


1. Create a new directory for your application and navigate to it in the terminal or using developer love VS Code 😊.


2. Create a folder ServerlessApiHandler where our lambda function code will lie, inside this folder create a file main.py and write down the below code in the file. You can modify your application code as per your need.


exports.lambdaEventHandler = async function(event) {
  const user = {
    "name": "kodeweich",
    "email": "kodeweicher@gmail.com"
  }
  return {
    statusCode: 200,
    body: JSON.stringify({ user: user })
  };
};


3. Now create a SAM template file, which is the heart of SAM, for now, named it template.yaml, which defines the resources that are going to deploy on your AWS server.


AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless Application Model Article

Parameters:
  ServerStage:
    Type: String
    Default: "test"
    AllowedValues:
      - "test" # for development environment
      - "v1" # for production environment

Globals:
  Function:
    Timeout: 5

Resources:
  ServerlessApplicationApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: "ServerlessApplicationApi"
      StageName: !Ref ServerStage
      Description: 'Serverless Application Api'
      EndpointConfiguration:
        Type: REGIONAL
      Cors:
        AllowMethods: "'GET, POST, OPTIONS, DELETE, PUT'"
        AllowOrigin: "'*'"
        AllowHeaders: "'Content-type, Authorization, X-APP-TOKEN'"

  # AWS IAM Role to allow lambda to PUT it's logs on CLOUDWATCH.
  ServerlessApiHandlerExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: ServerlessApiHandlerExecutionRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Policies:
        - PolicyName: LambdaExecutionandLogPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action: logs:CreateLogGroup
              Resource: "*"
            - Effect: Allow
              Action:
              - logs:CreateLogStream
              - logs:PutLogEvents
              Resource: "*"

  # A Lambda handler that will be be invoked using the API URL
  ServerlessApiHandler:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: ServerlessApiHandler
      CodeUri: ServerlessApiHandler/ 
      Handler: index.lambdaEventHandler
      Runtime: nodejs18.x
      Role: !GetAtt ServerlessApiHandlerExecutionRole.Arn
      Architectures:
        - x86_64
      Events:
        getUsers:
          Type: Api
          Properties:
            Path: /user
            Method: GET
            RestApiId:
              Ref: ServerlessApplicationApi

Outputs:
  ServerlessApplicationApi:
    Description: "API Gateway endpoint URL"
    Value: !Sub "https://${ServerlessApplicationApi}.execute-api.${AWS::Region}.amazonaws.com/${ServerStage}/"


The above code will create an API in AWS API Gateway, an IAM Role to allow lambda to put its log in the Cloud Watch, and a Lambda function which will be invoked by API Gateway API.


One of the key components of AWS SAM is the samconfig.toml file, which is used to manage environment-specific configuration for your serverless application. It is used by the AWS SAM CLI to deploy your application to AWS. The samconfig.toml file can be used to specify configuration information such as the AWS region, stack name, S3 bucket for storing deployment artifacts, and any other environment-specific configuration information.


4. Now let's create a samconfig.toml in the base directory of your project and write down the below code.


version = 0.1

[default]
region = "ap-south-1"
confirm_changeset = true

# allow SAM to crerate IAM roles
capabilities = ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"]


# configuration for testing environment
[test.deploy.parameters]
stack_name = "serverless-application-test-stack"
s3_bucket = "serverless-application-test-bucket"
s3_prefix = "serverless-application-test-stack"

# these paramter value will be mapped with template.yaml parameter section
parameter_overrides = ["ServerStage=test"]


# configuration for production environment
[prod.deploy.parameters]
stack_name = "serverless-application-prod-stack"
s3_bucket = "serverless-application-prod-bucket"
s3_prefix = "serverless-application-prod-stack"

# these paramter value will be mapped with template.yaml parameter section
parameter_overrides = ["ServerStage=v1"]


In this example, we have defined two environments, test, and prod, each with its own stack name and S3 bucket for storing the deployment artifacts. The default section is used to define the default region and capabilities for all environments. Before using this SAM config file make sure you have above mentioned S3 Bucket in your AWS account.


Deploy Your Project:-


Now with this SAM config file, you can deploy your testing and production environment using AWS SAM CLI. To deploy your application, you can simply run the below command specifying the environment as follow.


Testing Environment Deployment:-
sam build
sam deploy --config-env test --config-file samconfig.toml


Production Environment Deployment:-
sam build
sam deploy --config-env prod --config-file samconfig.toml


The AWS SAM CLI will use the configuration information in the specified environment to deploy your application, using the stack name and S3 bucket defined in the samconfig.toml file.


That's it your serverless application is up and running on the cloud using AWS SAM. Let's wrap up this article with a beautiful line on cloud computing.


“Cloud is about how you do computing, not where you do computing.” –Paul Maritz, VMware CEO



Conclusion:-


AWS SAM is a powerful yet easy-to-use serverless computing platform that provides developers with an intuitive and easy-to-use platform for creating, deploying, and managing serverless applications. The benefits of using AWS SAM include rapid development, automated deployments, easy access to resources, and the ability to track performance. With AWS SAM, developers can quickly deploy their projects and get them up and running in no time.