DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Keep Your Application Secrets Secret
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments
  • Automate Application Load Balancers With AWS Load Balancer Controller and Ingress
  • Performance Optimization for Multi-Layered Cloud Native AWS Application

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  • How AI Agents Are Transforming Enterprise Automation Architecture
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Building a Serverless Application on AWS With AWS SAM

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.

By 
Sandeepkumar Racherla user avatar
Sandeepkumar Racherla
·
Aug. 01, 23 · Analysis
Likes (2)
Comment
Save
Tweet
Share
5.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

By leveraging the power of AWS SAM, you can efficiently define and manage your serverless application's resources on AWS. Remember to clean up your resources when you're done experimenting to avoid unnecessary costs.

This step-by-step guide covered the basics, and there's much more you can do with AWS SAM and other AWS services. Continue exploring the official AWS SAM documentation and keep building exciting serverless applications. Happy coding!

AWS AWS Lambda Command-line interface YAML application Sam (text editor)

Opinions expressed by DZone contributors are their own.

Related

  • Keep Your Application Secrets Secret
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments
  • Automate Application Load Balancers With AWS Load Balancer Controller and Ingress
  • Performance Optimization for Multi-Layered Cloud Native AWS Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!