Introducing AWS SAM: Streamlining Serverless Development

Navya ANavya A
7 min read

Introduction:

In the ever-evolving landscape of cloud computing, serverless architecture has emerged as a transformative paradigm, enabling developers to focus on code rather than infrastructure. At the forefront of this revolution stands the AWS Serverless Application Model (SAM), a powerful framework designed to streamline the development, deployment, and management of serverless applications on Amazon Web Services (AWS).

In this guide, we embark on a journey through the realms of serverless computing, delving into the intricacies of AWS SAM and uncovering its potential to reshape the way we build and deploy applications in the cloud. From its fundamental principles to practical examples, we explore the core concepts of SAM, demystify its inner workings, and showcase its capabilities through hands-on demonstrations.

What is SAM?

SAM stands for Serverless Application Model. It is an open-source framework provided by Amazon Web Services (AWS) for building serverless applications. SAM extends AWS CloudFormation to provide a simplified way of defining serverless applications.

AWS SAM consists of two primary parts:

  1. AWS SAM template specification โ€“ An open-source framework that you can use to define your serverless application infrastructure on AWS.

  2. AWS SAM command line interface (AWS SAM CLI) โ€“ A command line tool that you can use with AWS SAM templates and supported third-party integrations to build and run your serverless applications.

Why SAM?

SAM simplifies the process of building serverless applications on AWS by providing shorthand syntaxes and pre-defined templates for common serverless resources such as AWS Lambda functions, Amazon API Gateway APIs, Amazon DynamoDB tables, and more. It allows developers to define their serverless applications using a declarative YAML syntax, making it easier to manage and deploy.

Using the AWS SAM syntax, you can define your infrastructure quickly, in fewer lines of code, and with a lower chance of errors. Its syntax is especially curated to abstract away the complexity in defining your serverless application infrastructure.

How SAM Works:

SAM works by extending AWS CloudFormation, which is AWS's service for infrastructure as code. SAM templates are essentially AWS CloudFormation templates with some additional serverless-specific capabilities and resources.

What is aws sam? | Lightnetics

SAM defines the following key components:

  1. Resources: These are the AWS resources that make up your serverless application, such as Lambda functions, DynamoDB tables, S3 buckets, etc.

  2. Events: Events trigger your Lambda functions. These can be API Gateway requests, S3 bucket uploads, DynamoDB table updates, etc.

  3. Functions: These are your Lambda functions, which contain the code that executes in response to events.

  4. APIs: If your application requires RESTful APIs, SAM can define them using Amazon API Gateway.

Benefits of using AWS SAM

Here are the benefits of using AWS SAM, simplified for better understanding:

  1. Simplified Infrastructure Definition:

    • With AWS SAM, you can define your application's infrastructure quickly and concisely using less code compared to traditional methods.
  2. Lifecycle Management:

    • Manage your serverless applications seamlessly throughout their entire development lifecycle.

    • Use the AWS SAM CLI to handle various phases such as authoring, building, deploying, testing, and monitoring.

  3. Efficient Permission Management:

    • AWS SAM connectors simplify the process of provisioning permissions between resources.

    • Define permissions in your AWS SAM templates, and AWS SAM automatically handles the IAM permissions required, making permission management easier.

  4. Streamlined Development Workflow:

    • Utilize the sam sync command to automatically synchronize local changes with the cloud as you develop.

    • This feature accelerates development and cloud testing workflows, ensuring that changes are reflected promptly.

  5. Terraform Support:

    • AWS SAM CLI extends support for managing Terraform serverless applications.

    • Perform local debugging and testing of Lambda functions and layers seamlessly using the AWS SAM CLI.

Common types of AWS SAM:

  1. AWS::Serverless::Function: Defines a Lambda function.

  2. AWS::Serverless::Api: Defines an API Gateway REST API.

  3. AWS::Serverless::HttpApi: Defines an HTTP API in API Gateway v2.

  4. AWS::Serverless::SimpleTable: Defines a DynamoDB table with basic settings.

  5. AWS::Serverless::StateMachine: Defines an AWS Step Functions state machine.

  6. AWS::Serverless::LayerVersion: Defines a Lambda layer version.

  7. AWS::Serverless::Application: Defines a nested application within the SAM template.

  8. AWS::Serverless::ApiGateway: Legacy resource type for defining an API Gateway REST API.

  9. AWS::Serverless::WebSocketApi: Defines a WebSocket API in API Gateway v2.

  10. AWS::Serverless::Model: Defines a model for use in API Gateway.

SAM CLI installation:

For installing SAM cli refer this documentation: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html

Example: Creating a DynamoDB Table using SAM:

Here's how you can define a DynamoDB table in a SAM template (template.yaml) and deploy it:

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

Resources:
  MyDynamoDBTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      TableName: MyTable
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5

In this SAM template:

  • We define a DynamoDB table named MyTable.

  • The table has a primary key id of type String.

  • Provisioned throughput is set to 5 read and write capacity units, which can be adjusted as per requirements.

  • An output is provided to display the name of the DynamoDB table created by this template.

To deploy this template, follow these steps:

  1. Save the above YAML content into a file named template.yaml.

  2. Install and configure the AWS SAM CLI if you haven't already.

  3. Open a terminal or command prompt.

  4. Navigate to the directory where your template.yaml file is located.

  5. Follow the steps to deploy the stack:

Deploying Serverless Applications with AWS SAM

AWS SAM provides multiple methods for deploying serverless applications to AWS Lambda and related services. In this blog post, we'll explore two common deployment methods using AWS SAM CLI: manual deployment using the sam package and sam deploy commands, and guided deployment using the sam deploy --guided command.

Method 1: Manual Deployment

Step 1: Configure AWS CLI

Before deploying your application, ensure you have configured your AWS CLI with the necessary credentials using the aws configure command. This step is essential for authenticating your requests to AWS services.

aws configure

Step 2: Package Your Application

Package your serverless application using the sam package command. This command bundles your application code and dependencies, uploads them to an S3 bucket, and generates a new SAM template with updated references to the packaged artifacts.

sam package --template-file template.yml --s3-bucket your-s3-bucket-name --output-template-file packaged-template.yml

Step 3: Deploy Your Application

Deploy your packaged application using the sam deploy command, specifying the path to your packaged SAM template and providing a stack name for your deployment.

sam deploy --template-file packaged-template.yml --stack-name your-stack-name

Method 2: Guided Deployment

Alternatively, you can use the guided deployment feature of the AWS SAM CLI to interactively configure and deploy your serverless application.

Step 1: Initiate Guided Deployment

Run the sam deploy --guided command in your terminal. This command initiates an interactive deployment process, prompting you to configure various deployment settings such as AWS Region, stack name, and other parameters.

sam deploy --guided

Step 2: Follow the Prompts

Follow the prompts provided by the guided deployment process to configure your deployment settings. Once you've provided the necessary information, the AWS SAM CLI will handle the deployment of your serverless application automatically.

Output:

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

    Looking for config file [samconfig.toml] :  Found
    Reading default arguments  :  Success

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

By following these deployment methods, you can efficiently deploy your serverless applications to AWS Lambda and related services using the AWS SAM CLI. Whether you prefer a manual approach or a guided deployment process, AWS SAM offers flexibility and convenience in managing your serverless infrastructure.

Conclusion:

In summary, AWS SAM revolutionizes serverless application development by offering streamlined deployment methods through its CLI. Whether opting for manual packaging and deployment or the guided approach, developers benefit from accelerated workflows and reduced complexities. By leveraging AWS SAM's capabilities, teams can focus on innovation, swiftly bringing their serverless applications to fruition with enhanced agility and efficiency.

0
Subscribe to my newsletter

Read articles from Navya A directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Navya A
Navya A

๐Ÿ‘‹ Welcome to my Hashnode profile! I'm a passionate technologist with expertise in AWS, DevOps, Kubernetes, Terraform, Datree, and various cloud technologies. Here's a glimpse into what I bring to the table: ๐ŸŒŸ Cloud Aficionado: I thrive in the world of cloud technologies, particularly AWS. From architecting scalable infrastructure to optimizing cost efficiency, I love diving deep into the AWS ecosystem and crafting robust solutions. ๐Ÿš€ DevOps Champion: As a DevOps enthusiast, I embrace the culture of collaboration and continuous improvement. I specialize in streamlining development workflows, implementing CI/CD pipelines, and automating infrastructure deployment using modern tools like Kubernetes. โ›ต Kubernetes Navigator: Navigating the seas of containerization is my forte. With a solid grasp on Kubernetes, I orchestrate containerized applications, manage deployments, and ensure seamless scalability while maximizing resource utilization. ๐Ÿ—๏ธ Terraform Magician: Building infrastructure as code is where I excel. With Terraform, I conjure up infrastructure blueprints, define infrastructure-as-code, and provision resources across multiple cloud platforms, ensuring consistent and reproducible deployments. ๐ŸŒณ Datree Guardian: In my quest for secure and compliant code, I leverage Datree to enforce best practices and prevent misconfigurations. I'm passionate about maintaining code quality, security, and reliability in every project I undertake. ๐ŸŒ Cloud Explorer: The ever-evolving cloud landscape fascinates me, and I'm constantly exploring new technologies and trends. From serverless architectures to big data analytics, I'm eager to stay ahead of the curve and help you harness the full potential of the cloud. Whether you need assistance in designing scalable architectures, optimizing your infrastructure, or enhancing your DevOps practices, I'm here to collaborate and share my knowledge. Let's embark on a journey together, where we leverage cutting-edge technologies to build robust and efficient solutions in the cloud! ๐Ÿš€๐Ÿ’ป