AWS Serverless Application Model (SAM) is a framework for defining and deploying serverless infrastructure on AWS. It provides simplified syntax for modeling serverless apps using CloudFormation templates. In this detailed guide, we dive deep into SAM deployment options focusing on the powerful sam deploy command.

AWS SAM Overview

Let‘s first briefly understand AWS SAM architecture and its components:

AWS SAM Architecture

SAM Template: YAML or JSON format template that defines the configuration for serverless app resources like:

  • AWS::Serverless::Function: Lambda functions
  • AWS::Serverless::Api: API Gateway endpoints
  • AWS::Serverless::SimpleTable: DynamoDB tables
  • AWS::SQS::Queue: SQS queues
  • AWS::Serverless::Application: Orchestrating higher level apps

The resources are defined using CloudFormation resource types but with simplified SAM syntax.

Transforms Header: Maps SAM resources to CloudFormation before deployment. Usually:

Transform: AWS::Serverless-2016-10-31

Metadata: Additional info like labels, tags, decorators etc.

Parameters: Input values to substitute in template during execution. Useful for reuse or customization.

With SAM templates, reusable serverless applications can be modeled infrastructure-as-code and deployed quickly via automated pipelines.

Next, we see how sam deploy helps with this.

Introduction to sam deploy

The SAM CLI provides the sam deploy command to deploy SAM apps to AWS. It handles:

  • Packaging code
  • Uploading artifacts to S3
  • Creating CloudFormation stacks
  • Managing stack changes and updates

It integrates seamlessly with SAM templates for automated deployment directly from local machine or CI/CD platforms.

The deploy command offers:

  1. Guided Interactive Mode: Step-by-step parameter configuration via prompts
  2. Non-Interactive Config File: Parameters preset in a samconfig.toml
  3. Advanced Customization: Fine-grained control over deployment behavior

Let‘s explore each approach:

Guided Deployment Walkthrough

The guided option interactively sets up a deployment:

sam deploy --guided

Sample execution flow:

sam deploy guided

Configuration prompts:

  • Stack Name: Pick a name for the CloudFormation stack
  • AWS Region: Select the target region like us-east-1
  • Confirm changes: Check this to manual verify changes
  • SAM role: Allow automatically creating IAM role with permissions needed

As we go through the questions, SAM handles all the heavy lifting – packaging code, uploading to S3, configuring permissions etc.

Finally a change set is presented to confirm all modifications before deploying the stack.

Non-Interactive Deployment

For CI/CD pipelines, guided inputs don‘t work.

Instead, a configuration file can be used:

samconfig.toml:

[default]
region = "us-east-1"

[myapp]
stack_name = "sam-app-stack"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-abcdefghi"
s3_prefix = "myapp" 
region = "us-east-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
parameter_overrides = "Param1=Value1 Param2=Value2"

Now the deployment command becomes:

sam deploy --config-file samconfig.toml

This allows non-interactive deployment by loading parameters from configuration.

Advanced Customization

The sam deploy command provides further customization options to control deployment behavior as per different applications needs:

Packaging Configurations

Fine-tune where and how SAM packages your source code, dependencies etc:

# Skip packaging to reuse existing artifacts
sam deploy --no-package 

# Custom S3 bucket  
sam deploy --s3-bucket my-deploy-bucket

# Folder path prefix format in S3
sam deploy --s3-prefix myapp/v1 

Change Set Controls

Manage stack changes more granularly before deploy:

# Generate but don‘t execute change set
sam deploy --no-execute-changeset  

# Fail if no changes detected in stack  
sam deploy --fail-on-empty-changeset  

Capability Flags

Expand IAM privileges for resources that need it:

# Allow creating custom IAM roles
sam deploy --capability-iam

# Automatically approve IAM capability  
sam deploy --no-confirm-changeset

Parameter Override

Override template parameter values:

# Set param value as test  
sam deploy --parameter-overrides MyParam=test

These allow fine-grained control over deployment to suit different applications.

Best Practices for Production Deployments

When deploying SAM applications to production, keep in mind:

1. Least Privilege Access

Grant minimum permissions via SAM policy templates instead of AdministratorAccess:

# Example SAM policy for API Gateway invocation
APIGatewayInvokeFullAccess: 
  Type: ‘AWS::Serverless::Application‘
  Properties:
    Policies:
      - Version: ‘2012-10-17‘  
        Statement:
          - Effect: Allow
            Action:
              - ‘execute-api:Invoke‘
              - ‘execute-api:ManageConnections‘
            Resource: 
              Fn::Join:
                - ‘‘
                - - ‘arn:aws:execute-api:‘
                  - Ref: AWS::Region
                  - ‘:‘
                  - Ref: AWS::AccountId
                  - ‘:‘
                  - Ref: MyAPI  

2. CI/CD Integration

Embed sam deploy commands in CI/CD system via Bash, PowerShell scripts triggering automated builds.

Example GitHub Actions workflow:

on: push 

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: aws-actions/setup-sam@v2
      - run: sam deploy --no-confirm-changeset

3. Validation & Testing

Add integration test stage after deploy to call APIs and validate responses. Consider canary testing before general availability.

4. Monitoring & Alerts

Use tools like AWS X-Ray, CloudWatch alarms for application monitoring. Plot key metrics in dashboards tracking latency, errors, invoke counts etc.

5. Cost Optimization

Right size Lambda memory allocations. Set up auto-scaling rules. Turn off dev resources when not in use.

Adopting these best practices will improve reliability, reduce overhead and lower costs.

Example Deployment Flow

As a hands-on example, let‘s deploy a simple SAM app with an API endpoint and Lambda function:

1. SAM Template

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

Resources:

  HelloWorldFunction: 
    Type: ‘AWS::Serverless::Function‘
    Properties:
      Handler: app.handler
      Runtime: python3.7
      CodeUri: ./

  HelloWorldApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod 
      DefinitionUri: openapi.yml

Outputs:

  ApiURL:
    Description: API endpoint 
    Value: !Sub ‘https://${HelloWorldApi}.execute-api.${AWS::Region}.amazonaws.com/prod‘

2. Lambda Function Code

# app.py

def handler(event, context):

  return {
    ‘statusCode‘: 200,
    ‘body‘: ‘Hello World!‘  
  }

3. Build & Package

Bundle source code into S3-hosted artifacts:

sam build

4. Guided Deployment

sam deploy --guided

Walk through the guided prompts to deploy resources.

5. Testing

Fetch the API URL output and validate response:

curl https://abcd123ef.execute-api.us-east-1.amazonaws.com/prod

# Hello World!

This covers a simple serverless application deployment with SAM end-to-end.

Now let‘s recap some key takeaways.

Conclusion

Deploying serverless applications with AWS SAM deploy offers a streamlined mechanism for getting code live on AWS infrastructure. Its guided prompts and config file options integrate seamlessly with automated devops pipelines.

Advanced power users can further control behavior through parameters like:

  • Custom S3 bucket configurations
  • Change set validations
  • Overriding template parameters
  • Enabling extended IAM privileges

For production deployments, best practices around monitoring, testing, access controls and cost management should be implemented.

Overall, AWS SAM standardized templates combined with sam deploy capabilities provide a robust model for managing the entire lifecycle of serverless applications. Automated infrastructure as code allows focusing on writing business logic while leaving provisioning, scaling and administration to Cloud vendors. This drives faster development and easier maintenance – two key benefits of the serverless model.

Similar Posts