What is AWS Serverless Application Model(SAM) ? Everything You Need to Know

Dear Reader, Hope you are doing great. In today’s post, I will discuss about AWS Serverless Application Model or AWS SAM. In addition to that, I will also discuss, how it can make your life easier as a developer while creating and deploying a serverless application on AWS.

Are you thinking what the hell is this serverless application?

If you have already worked on it, I can see a smile on your face. If not, don’t worry, I am here to help you πŸ™‚

Please note that, this post is an introduction to Serverless Application Model or AWS SAM. If you say, I can come up with a follow up tutorial on developing lambdas using SAM. What say??

Alright, let’s get to know about serverless application.

What exactly is a serverless application?

In a layman’s term, If I say, serverless application is an application where you just worry about writing your code or business logic. And, You need not worry about the underlying infrastructure on which your code is gonna run.

For example- A back-end application using AWS Lambda

Lambda is the serverless compute service provided by AWS which lets you run code without managing any server.

Important Note: Please note that, it’s not like there are no server needed, it’s just that you don’t provision/manage them. Apart from them, serverless application doesn’t mean just a lambda function. Rather a serverless app will be a combination of Lambda, event sources, database etc.

In other words, in terms of AWS, a serverless application is made up of various serverless services provided by AWS. For example a back-end application using Lambda, API Gateway, S3 and DynamoDB is a serverless application.

Suggested Read: Serverless Services on AWS: Complete List With Explanation

You know serverless application now. So, if you are interested in serverless development on AWS, you must checkout SAM. SAM is magical for serverless apps development, deployment on AWS and testing them in your local system.

What is AWS Serverless Application Model(SAM)?

AWS SAM or Serverless Application Model is an open source framework that you can use to develop, build and deploy your serverless applications. It is build on the top of CloudFormation and provides shorthand and simplified syntax to define your serverless application components such as lambda functions, API Gateway , DynamoDB etc.

So basically, it lets you leverage CloudFormation to create and manage your serverless infra but with easy to use syntax and quite less amount of code. We will see this in later section πŸ™‚

How does SAM work?

You describe your application resources such as Lambda, API Gateway, DynamoDB tables etc using the shorthand syntax provided by SAM in your template for example template.yml

When you deploy your application, SAM transforms the template to CloudFormation syntax and then CloudFormation creates your resources as a single stack.

Why AWS SAM came into picture?

Before using anything we all like to ask this question. All is going well, why do I even need this?

Imagine you have a large serverless application which contains hundreds of lambda function, API Gateway, DynamoDB table for data , S3 bucket SQS queues etc.

You can create and manage them-

  • Using console but it’s too cumbersome
  • You develop locally and upload your code to lambda to test

What’s the issue with above approach?

  • It will take a lot of time to test even small code changes and deployment will take time
  • Hard to manage all the resources together
  • Reproducing the infra in another region or account such as non prod or prod, you need to create all of them again
  • Local testing is not possible for lambda

Do you think it’s even feasible to exactly mimic the infra that we have in dev account into prod using console?

I am sure, your answer is a Big No.

Considering the huge fan following of AWS Lambda and serverless way of application modernization and because many of AWS client faced these issue. AWS came up with SAM.

And, That’s when SAM came into picture.

To be honest with you, the very first time I deployed my lambda with API gateway and dynamodb using SAM, It simply blew my mind. Everything seemed magical to me. πŸ™‚

How does SAM solves all the above mentioned issues?

It solves above mentioned issues by letting you-

  • Define your infrastructure as code using template and version them in your favorite code repository.
  • Syntax is simple and straight forward as compared to CloudFormation
  • Develop, build, deploy, test and debug lambda function in your local system using SAM CLI
  • Let’s you use SAM resources as well as leverage all CloudFormation resources and features to extend your template capability even more
  • Use other dev tools at AWS such as Cloud9, CodeBuild, CodeDeploy, CodePipeline, Codestar etc.
  • You can use AWS Serverless Application Repository to find existing sample applications.
  • Use Cloud9 which is a browser based IDE on AWS can be used to develop and test your application.
  • You can use CodeBuild, CodeDeploy and CodePipeline for continous integration and delivery. You can also use Codestar to get started with a sample project repo with project structure and ready to use fully working CICD pipeline

Components of AWS SAM

By now, you might have guessed the components.

AWS SAM majorly comes in two components.

  • SAM Template Specification: A template which you can use to define your serverless application components
    • Provides shorthand syntax to describe your functions, event sources etc.
    • SAM templates are extension of CloudFormation
    • They must contain a transform Transform: AWS::Serverless-2016-10-31  to indicate that the file is a SAM template file
    • Can be used as single deployable versioned entity
    • During deployment they get converted to CloudFormation
    • In the end you leverage CloudFormation to create and manage your resources but with a lot less amount of code
  • AWS SAM CLI: A CLI which which you can use to create a serveless application from scratch, build it and deploy on AWS all from your command line locally
    • You can use SAM CLI to bootstrap a serverless application
    • You can test your lambda locally in your machine provided you have docker installed
    • You can package your application and deploy on AWS cloud all using SAM CLI
    • Check example documentation to get started with SAM CLI

Supported resources by SAM

At the time of writing this tutorial below are the SAM specific resources supported by SAM, But please feel free to refer documentation for updated list of resources.

Important Note: Please don’t think that these are the only resource that you can use in your SAM template. As I already said you can use these + All the resources supported by CloudFormation which you can find here.

Therefore,

SAM supported Resources = SAM specific resources + Resources supported by CloudFormation

Why SAM template and not CloudFormation Straightaway?

Alright, at this point of time you might say when in the end everything will be done by CloudFormation , why to use a SAM template?

For local and all , SAM CLI is fine but why don’t we leverage CloudFormation template itself as template.

Well, you are absolutely right and of course you can do it. But for creating and deploying a simple lambda function the CloudFormation template is gonna be huge with lot’s of dependent resources.

Let’s see an example below-

A simple HelloWorld Lambda with API Gateway Event Source Using SAM Template:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for lambda

Globals:
  Function:
    Timeout: 3
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri:
        Bucket: Bucket
        Key: Code Key
      Handler: app.lambda_handler
      Runtime: python3.7
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

As you can see, template has barely 20 lines and it’s quite clean with a single resource. As we know, on deploy above SAM, template is transformed into CloudFormation template and then whole infra is created as a single stack.

Would you like to see the transformed template?

I am sure your answer is yes !!!

So, Here you go ………

A simple HelloWorld Lambda with API Gateway Event Source Using CloudFormation:

AWSTemplateFormatVersion: 2010-09-09
Description: Sample SAM Template for lambda

Resources:
  HelloWorldFunctionHelloWorldPermissionProd:
    Type: 'AWS::Lambda::Permission'
    Properties:
      Action: 'lambda:InvokeFunction'
      Principal: apigateway.amazonaws.com
      FunctionName: !Ref HelloWorldFunction
      SourceArn: !Sub 
        - >-
          arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId__}/${__Stage__}/GET/hello
        - __Stage__: '*'
          __ApiId__: !Ref ServerlessRestApi
  HelloWorldFunctionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
      Tags:
        - Value: SAM
          Key: 'lambda:createdBy'
  ServerlessRestApiProdStage:
    Type: 'AWS::ApiGateway::Stage'
    Properties:
      DeploymentId: !Ref ServerlessRestApiDeployment47fc2d5f9d
      RestApiId: !Ref ServerlessRestApi
      StageName: Prod
  ServerlessRestApiDeployment47fc2d5f9d:
    Type: 'AWS::ApiGateway::Deployment'
    Properties:
      RestApiId: !Ref ServerlessRestApi
      Description: 'RestApi deployment id'
      StageName: Stage
  ServerlessRestApi:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Body:
        info:
          version: '1.0'
          title: !Ref 'AWS::StackName'
        paths:
          /hello:
            get:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri: !Sub >-
                  arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${HelloWorldFunction.Arn}/invocations
              responses: {}
        swagger: '2.0'
  HelloWorldFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code:
        S3Bucket: Bucket for code
        S3Key: CodeKey
      Tags:
        - Value: SAM
          Key: 'lambda:createdBy'
      Handler: app.lambda_handler
      Role: !GetAtt 
        - HelloWorldFunctionRole
        - Arn
      Timeout: 3
      Runtime: python3.7
	  
Outputs:
  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/

The transformed template is quite huge. Now you see behind the scene how many resources got created? There are many. You see how complex it will be to create a small lambda using CloudFormation.

Did I convince you to use SAM template??

Well, do try them, and I am sure, you will fall in love with it.

Conclusion

At last, I would like to say that If you are into serverless application development on AWS using lambda or Lambda with API Gateway. You must try SAM templates to describe your resourcses.

Also, If you are interested in local development, use SAM CLI for the same. It can help to quickly get started with lambda skeletan code and help you deploy and test locally.

Well, That was my take on AWS Serverless Application Model. Do let me know If you have used it? If yes- What is your thought on AWS SAM?

Would you like me to come up with a hands on post on getting started with AWS SAM CLI? Do let me know in comments and I would to happy to do that for you.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

If you liked reading my post, you can motivate me by-

Suggested Read:

One thought on “What is AWS Serverless Application Model(SAM) ? Everything You Need to Know

Leave a Reply

Your email address will not be published. Required fields are marked *