Building a Serverless Application on AWS With AWS SAM

Learn how to define AWS resources like Lambda functions, SQS queues, and SNS topics, set up event triggers, create IAM roles, and deploy the SAM application effortlessly.

Welcome to this step-by-step guide on building a serverless application on AWS using AWS SAM (Serverless Application Model). In this tutorial, we will walk you through the process of defining and managing AWS resources, such as AWS Lambda functions, SQS queues, and SNS topics, using SAM template model code. Additionally, we'll set up an event trigger for the Lambda function using the SQS queue, create a new IAM role with the necessary permissions, and deploy the SAM application to AWS.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  • Python: Ensure you have Python installed on your computer. You can download it from the official Python website.  
  • An AWS Account: If you don't have one, sign up for an AWS account.
  • AWS CLI: Install the AWS Command Line Interface on your computer to interact with AWS services from your terminal.
  • AWS SAM CLI: Install the AWS SAM CLI, which provides additional tools for managing serverless applications.

Step-by-Step Walkthrough

1. Create a new directory for your SAM application.

Shell

mkdir MySAMApp
cd MySAMApp 

2. Create a new file named "template.yaml" within the "MySAMApp" directory. This file will contain the SAM template model code.

3. Let's go through the SAM template and understand each section:

YAML

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

 

  • The AWSTemplateFormatVersion specifies the version of the CloudFormation template format we are using. It's set to '2010-09-09' here.
  • The Transform section indicates the macro or template name that CloudFormation should use to process this template. We're using the 'AWS::Serverless-2016-10-31' transform, which is specific to SAM templates.
  • The Description is optional and provides a brief description of the template.

Next, we define our AWS resources:

YAML

Resources:
  MyLambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      CodeUri: my-lambda/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        MyApi:
          Type: Api
          Properties:
            Path: /my-api
            Method: GET 

 

  • We define an AWS Lambda function named MyLambdaFunction. The AWS::Serverless::Function type is specific to SAM and simplifies the creation of Lambda functions.
  • The CodeUri specifies the path to the folder containing the Lambda function code, which we'll create shortly.
  • The Handler indicates the entry point of our Lambda function, which is the lambda_handler function defined in the "app.py" file.
  • Runtime specifies the programming language runtime for the Lambda function, in this case, Python 3.8.
  • Under Events, we create an API Gateway event trigger named MyApi, which listens for HTTP GET requests on the "/my-api" endpoint.

Next, we define an SQS queue and an SNS topic:

YAML

  MySqsQueue:
    Type: 'AWS::SQS::Queue'
    Properties:
      QueueName: my-sqs-queue
 
  MySnsTopic:
    Type: 'AWS::SNS::Topic'
    Properties:
      DisplayName: MySnsTopic
      TopicName: my-sns-topic 
  • The MySqsQueue is an AWS SQS queue created using the AWS::SQS::Queue resource type. We set the QueueName to "my-sqs-queue."
  • The MySnsTopic is an AWS SNS topic created using the AWS::SNS::Topic resource type. We set the DisplayName to "MySnsTopic" and then TopicName to "my-sns-topic."

Next, we create an event source mapping between the SQS queue and the Lambda function:

YAML

  MySqsQueueEvent:
    Type: 'AWS::Lambda::EventSourceMapping'
    Properties:
      BatchSize: 1
      EventSourceArn:
        Fn::GetAtt: [MySqsQueue, Arn]
      FunctionName:
        Ref: MyLambdaFunction 
  • The MySqsQueueEvent is an AWS Lambda event source mapping created using the AWS::Lambda::EventSourceMapping resource type.
  • We set BatchSize to 1, indicating that one message at a time will trigger the Lambda function.
  • The EventSourceArn is set to the ARN (Amazon Resource Name) of the SQS queue we defined earlier.
  • The FunctionName is set to the logical ID of the Lambda function resource (MyLambdaFunction) using the Ref function.

Finally, we create a new IAM role for our Lambda function:

YAML

  MyLambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: my-lambda-role
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonS3FullAccess'
        - 'arn:aws:iam::aws:policy/AmazonSQSFullAccess'
        - 'arn:aws:iam::aws:policy/AmazonSNSFullAccess' 
  • The MyLambdaRole is an AWS IAM role created using the AWS::IAM::Role resource type. This role grants permissions to the Lambda function.
  • We specify the RoleName as "my-lambda-role."
  • The AssumeRolePolicyDocument allows the Lambda service to assume this role and execute our function. We grant this permission to lambda.amazonaws.com.
  • Under ManagedPolicyArns, we attach managed policies that provide full access to Amazon S3, SQS, and SNS. Be cautious when using such broad permissions in a production environment.

4. Create a new directory named "my-lambda" within the "MySAMApp" directory. This directory will hold the Lambda function code.

5. Create a new file named "app.py" inside the "my-lambda" directory. This file contains the Lambda function code.

Python

import json
 
def lambda_handler(event, context):
    for record in event['Records']:
        # Process the received message from the SQS queue
        message_body = record['body']
        print(f"Received message: {message_body}")
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from AWS Lambda!')
    }

 

  • The lambda_handler function is the entry point for our Lambda function.
  • It receives an event and context as input parameters.
  • The function processes each message received from the SQS queue and prints the message body.
  • It returns a response with a status code of 200 and a simple JSON message, "Hello from AWS Lambda!".

6. Build and package the SAM application:

Shell

sam build

 

7. Deploy the SAM application to AWS:

Shell

sam deploy --guided

 

Follow the prompts during the deployment process. You will be asked to provide parameters such as the AWS Region, Stack Name, and other configuration details.

Conclusion

Congratulations! You've successfully created AWS Lambda functions, SQS queues, and SNS topics using the AWS SAM template model code. Additionally, you set up an event trigger for the Lambda function using the SQS queue, created a new IAM role with the necessary permissions, and deployed the SAM application to AWS.

We Provide consulting, implementation, and management services on DevOps, DevSecOps, DataOps, Cloud, Automated Ops, Microservices, Infrastructure, and Security

 

Services offered by us: https://www.zippyops.com/services

Our Products: https://www.zippyops.com/products

Our Solutions: https://www.zippyops.com/solutions

For Demo, videos check out YouTube Playlist: https://www.youtube.com/watch?v=4FYvPooN_Tg&list=PLCJ3JpanNyCfXlHahZhYgJH9-rV6ouPro

 

If this seems interesting, please email us at [email protected] for a call.




Relevant Blogs:





Recent Comments

No comments

Leave a Comment