Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Deep Dive into AWS SAM

264 views

Published on

AWS Serverless Application Model (SAM) is a template driven tool for creating and managing serverless applications. In just a few lines of code you can define complex AWS Lambda based serverless applications, security permissions, and advanced configuration capabilities. Join us as we dive deep into best practices and tricks for using SAM at scale, including how to make the most of the dynamic template capabilities of SAM, how to use advanced features such as deployment preferences and policy templates, and how to debug serverless applications with SAM CLI.

Speaker: Chris Munns - Principal Developer Advocate, AWS Serverless Applications, AWS

  • Be the first to comment

Deep Dive into AWS SAM

  1. 1. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Pop-up Loft Deep Dive into AWS SAM and AWS SAM CLI Chris Munns Principal Developer Advocate AWS Serverless
  2. 2. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved About me: Chris Munns - munns@amazon.com, @chrismunns – Principal Developer Advocate - Serverless – New Yorker – Previously: • AWS Business Development Manager – DevOps, July ’15 - Feb ‘17 • AWS Solutions Architect Nov, 2011- Dec 2014 • Formerly on operations teams @Etsy and @Meetup • Little time at a hedge fund, Xerox and a few other startups – Rochester Institute of Technology: Applied Networking and Systems Administration ’05 – Internet infrastructure geek
  3. 3. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved https://secure.flickr.com/photos/mgifford/4525333972 Why are we here today?
  4. 4. Meet SAM!
  5. 5. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Serverless Application Model (SAM) AWS CloudFormation extension optimized for serverless Special serverless resource types: functions, APIs, tables, Layers and Applications Supports anything AWS CloudFormation supports Open specification (Apache 2.0) https://aws.amazon.com/serverless/sam NEW!
  6. 6. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Serverless applications Services (anything) Changes in data state Requests to endpoints Changes in resource state Event source Function Node.js Python Java C# Go Ruby Runtime APINEW!
  7. 7. SAM Template AWSTemplateFormatVersion: '2010-09-09’ Transform: AWS::Serverless-2016-10-31 Resources: GetHtmlFunction: Type: AWS::Serverless::Function Properties: CodeUri: s3://sam-demo-bucket/todo_list.zip Handler: index.gethtml Runtime: nodejs6.10 Policies: AmazonDynamoDBReadOnlyAccess Events: GetHtml: Type: Api Properties: Path: /{proxy+} Method: ANY ListTable: Type: AWS::Serverless::SimpleTable
  8. 8. SAM Template Tells AWS CloudFormation this is a SAM template it needs to “transform” Creates a AWS Lambda function with the referenced managed AWS IAM policy, runtime, code at the referenced zip location, and handler as defined. Also creates an Amazon API Gateway and takes care of all mapping/permissions necessary Creates a Amazon DynamoDB table with 5 Read & Write units AWSTemplateFormatVersion: '2010-09-09’ Transform: AWS::Serverless-2016-10-31 Resources: GetHtmlFunction: Type: AWS::Serverless::Function Properties: CodeUri: s3://sam-demo-bucket/todo_list.zip Handler: index.gethtml Runtime: nodejs6.10 Policies: AmazonDynamoDBReadOnlyAccess Events: GetHtml: Type: Api Properties: Path: /{proxy+} Method: ANY ListTable: Type: AWS::Serverless::SimpleTable
  9. 9. https://github.com/awslabs/aws-serverless-samfarm/blob/master/api/saml.yaml <-THIS BECOMES THIS-> AWS SAM Templates
  10. 10. AWS SAM Template Properties Handler: index.js Runtime: nodejs4.3 CodeUri: 's3://my-code-bucket/my-function.zip' Description: Creates thumbnails of uploaded images MemorySize: 1024 Timeout: 15 Policies: AmazonS3FullAccess Environment: Variables: TABLE_NAME: my-table Events: PhotoUpload: Type: S3 Properties: Bucket: my-photo-bucket Tracing: Active|PassThrough Tags: AppNameTag: ThumbnailApp DepartmentNameTag: ThumbnailDepartmentFrom SAM Version 2016-10-31 AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable AWS::Serverless::LayerVersion AWS::Serverless::Application
  11. 11. AWS SAM Template Properties StageName: prod DefinitionUri: swagger.yml CacheClusterEnabled: true CacheClusterSize: 28.4 EndpointConfiguration: REGIONAL Variables: VarName: VarValue From SAM Version 2016-10-31 AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable AWS::Serverless::LayerVersion AWS::Serverless::Application
  12. 12. AWS SAM Template Properties PrimaryKey: Name: id Type: String ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 Tags: Department: Engineering AppType: Serverless SSESpecification: SSEEnabled: true From SAM Version 2016-10-31 AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable AWS::Serverless::LayerVersion AWS::Serverless::Application
  13. 13. AWS SAM Template Properties Properties: LayerName: MyLayer Description: Layer description ContentUri: 's3://my-bucket/my- layer.zip' CompatibleRuntimes: - nodejs6.10 - nodejs8.10 LicenseInfo: 'Available under the MIT-0 license.' RetentionPolicy: Retain From SAM Version 2016-10-31 AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable AWS::Serverless::LayerVersion AWS::Serverless::Application NEW!
  14. 14. AWS SAM Template Properties Resources: MyApplication: Properties: Location: ApplicationId: 'arn:aws:serverlessrepo:us-east- 1:012345678901:applications/my- application' SemanticVersion: 1.0.0 Parameters: StringParameter: parameter-value IntegerParameter: 2 From SAM Version 2016-10-31 AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable AWS::Serverless::LayerVersion AWS::Serverless::Application NEW!
  15. 15. Note: Events are a map of string to Event Source Object Event Source Objects have the following structure: Type: Properties: For Example: Events: MyEventName: Type: S3 Properties: Bucket: my-photo-bucket AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill From SAM Version 2016-10-31
  16. 16. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template EC2InstanceSample: **WARNING** This template an Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type" : "String" }, "Environment": { "Type" : "String", "Default" : ”Dev", "AllowedValues" : [”Mgmt", "Dev", ”Staging", "Prod"], "Description" : "Environment that the instances will run in.” } }, "Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-7f418316" }, "us-west-2" : { "AMI" : "ami-16fd7026" } } }, "Conditions" : { ”EnableEBSOptimized" : {"Fn::Equals" : [{"Ref" : " Environment "}, ”Prod"]}, }, "Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "EbsOptimized " : {"Fn::If": [ " EnableEBSOptimized ", {“true”}, {“false”}]}, "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "UserData" : { "Fn::Base64" : "80" } } } }, "Outputs" : { "InstanceId" : { "Description" : "InstanceId of the newly created EC2 instance", "Value" : { "Ref" : "Ec2Instance" } }, "PublicDNS" : { "Description" : "Public DNSName of the newly created EC2 instance", "Value" : { "Fn::GetAtt" : [ "Ec2Instance", "PublicDnsName" ] } } } }
  17. 17. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template EC2InstanceSample: **WARNING** This template an Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type" : "String" }, "Environment": { "Type" : "String", "Default" : ”Dev", "AllowedValues" : [”Mgmt", "Dev", ”Staging", "Prod"], "Description" : "Environment that the instances will run in.” } }, "Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-7f418316" }, "us-west-2" : { "AMI" : "ami-16fd7026" } } }, "Conditions" : { ”EnableEBSOptimized" : {"Fn::Equals" : [{"Ref" : " Environment "}, ”Prod"]}, }, "Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "EbsOptimized " : {"Fn::If": [ " EnableEBSOptimized ", {“true”}, {“false”}]}, "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "UserData" : { "Fn::Base64" : "80" } } } }, "Outputs" : { "InstanceId" : { "Description" : "InstanceId of the newly created EC2 instance", "Value" : { "Ref" : "Ec2Instance" } }, "PublicDNS" : { "Description" : "Public DNSName of the newly created EC2 instance", "Value" : { "Fn::GetAtt" : [ "Ec2Instance", "PublicDnsName" ] } } } } HEADERS PARAMETERS MAPPINGS RESOURCES OUTPUTS CONDITIONALS
  18. 18. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template EC2InstanceSample: **WARNING** This template an Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type" : "String" }, "Environment": { "Type" : "String", "Default" : ”Dev", "AllowedValues" : [”Mgmt", "Dev", ”Staging", "Prod"], "Description" : "Environment that the instances will run in.” } }, "Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-7f418316" }, "us-west-2" : { "AMI" : "ami-16fd7026" } } }, "Conditions" : { ”EnableEBSOptimized" : {"Fn::Equals" : [{"Ref" : " Environment "}, ”Prod"]}, }, "Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "EbsOptimized " : {"Fn::If": [ " EnableEBSOptimized ", {“true”}, {“false”}]}, "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "UserData" : { "Fn::Base64" : "80" } } } }, "Outputs" : { "InstanceId" : { "Description" : "InstanceId of the newly created EC2 instance", "Value" : { "Ref" : "Ec2Instance" } }, "PublicDNS" : { "Description" : "Public DNSName of the newly created EC2 instance", "Value" : { "Fn::GetAtt" : [ "Ec2Instance", "PublicDnsName" ] } } } } Description of what your stack does, contains, etc Provision time values that add structured flexibility and customization Pre-defined conditional case statements Conditional values set via evaluations of passed references AWS resource definitions Resulting attributes of stack resource creation HEADERS PARAMETERS MAPPINGS RESOURCES OUTPUTS CONDITIONALS
  19. 19. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM Template Capabilities • Can mix in other non-SAM CloudFormation resources in the same template • i.e. Amazon S3, Amazon Kinesis, AWS Step Functions • Supports use of Parameters, Mappings, Outputs, etc • Supports Intrinsic Functions • Can use ImportValue (exceptions for RestApiId, Policies, StageName attributes) • YAML or JSON
  20. 20. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Lambda Environment Variables • Key-value pairs that you can dynamically pass to your function • Available via standard environment variable APIs such as process.env for Node.js or os.environ for Python • Can optionally be encrypted via AWS Key Management Service (KMS) • Allows you to specify in IAM what roles have access to the keys to decrypt the information • Useful for creating environments per stage (i.e. dev, testing, production)
  21. 21. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Amazon API Gateway Stage Variables • Stage variables act like environment variables • Use stage variables to store configuration values • Stage variables are available in the $context object • Values are accessible from most fields in API Gateway • Lambda function ARN • HTTP endpoint • Custom authorizer function name • Parameter mappings
  22. 22. AWS Lambda and Amazon API Gateway Variables + AWS SAM Parameters: MyEnvironment: Type: String Default: testing AllowedValues: - testing - staging - prod Description: Environment of this stack of resources Mappings: SpecialFeature1: testing: status: on staging: status: on prod: status: off #Lambda MyFunction: Type: 'AWS::Serverless::Function' Properties: … Environment: Variables: ENVIRONMENT: !Ref: MyEnvironment Spec_Feature1: !FindInMap [SpecialFeature1, !Ref MyEnvironment, status] … #API Gateway MyApiGatewayApi: Type: AWS::Serverless::Api Properties: … Variables: ENVIRONMENT: !Ref: MyEnvironment
  23. 23. Parameters: MyEnvironment: Type: String Default: testing AllowedValues: - testing - staging - prod Description: Environment of this stack of resources Mappings: SpecialFeature1: testing: status: on staging: status: on prod: status: off #Lambda MyFunction: Type: 'AWS::Serverless::Function' Properties: … Environment: Variables: ENVIRONMENT: !Ref: MyEnvironment Spec_Feature1: !FindInMap [SpecialFeature1, !Ref MyEnvironment, status] … #API Gateway MyApiGatewayApi: Type: AWS::Serverless::Api Properties: … Variables: ENVIRONMENT: !Ref: MyEnvironment AWS Lambda and Amazon API Gateway Variables + AWS SAM
  24. 24. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Stage Variables and AWS Lambda Aliases Using Stage Variables in API Gateway together with Lambda function Aliases you can manage a single API configuration and Lambda function for multiple environment stages myLambdaFunction 1 2 3 = prod 4 5 6 = beta 7 8 = dev My First API Stage variable = lambdaAlias Prod lambdaAlias = prod Beta lambdaAlias = beta Dev lambdaAlias = dev
  25. 25. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Lambda Alias Traffic Shifting myLambdaFunction 1 2 3 = prod 4 5 6 = prod 5% My First API Stage variable = lambdaAlias Prod lambdaAlias = prod
  26. 26. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM + Safe Deployments MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs6.10 AutoPublishAlias: !Ref ENVIRONMENT DeploymentPreference: Type: Linear10PercentEvery10Minutes Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: # Validation Lambda functions that are run before & after traffic shifting PreTraffic: !Ref PreTrafficLambdaFunction PostTraffic: !Ref PostTrafficLambdaFunction
  27. 27. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM + Safe Deployments MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs6.10 AutoPublishAlias: !Ref ENVIRONMENT DeploymentPreference: Type: Linear10PercentEvery10Minutes Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: # Validation Lambda functions that are run before & after traffic shifting PreTraffic: !Ref PreTrafficLambdaFunction PostTraffic: !Ref PostTrafficLambdaFunction
  28. 28. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Lambda Alias Traffic Shifting & AWS SAM AutoPublishAlias By adding this property and specifying an alias name, AWS SAM will do the following: • Detect when new code is being deployed based on changes to the Lambda function's Amazon S3 URI. • Create and publish an updated version of that function with the latest code. • Create an alias with a name you provide (unless an alias already exists) and points to the updated version of the Lambda function. Deployment Preference Type Canary10Percent30Minutes Canary10Percent5Minutes Canary10Percent10Minutes Canary10Percent15Minutes Linear10PercentEvery10Minutes Linear10PercentEvery1Minute Linear10PercentEvery2Minutes Linear10PercentEvery3Minutes AllAtOnce In SAM:
  29. 29. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Lambda Alias Traffic Shifting & AWS SAM Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: # Validation Lambda functions that are run before & after traffic shifting PreTraffic: !Ref PreTrafficLambdaFunction PostTraffic: !Ref PostTrafficLambdaFunction Note: You can specify a maximum of 10 alarms In SAM:
  30. 30. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS Lambda Alias Traffic Shifting myLambdaFunction 1 ... 6 = prod My First API Stage variable = lambdaAlias Prod lambdaAlias = prod
  31. 31. Globals: Function: Runtime: nodejs6.10 CodeUri: s3://code-artifacts/pet_app1234.zip MemorySize: 1024 Timeout: 30 AutoPublishAlias: !Ref ENVIRONMENT getDogsFunction: Type: AWS::Serverless::Function Properties: Handler: getdogs.handler Events: GetDogs: Type: Api Properties: Path: /Dogs Method: ANY getCatsFunction: Type: AWS::Serverless::Function Properties: Handler: getCats.handler Events: GetCats: Type: Api Properties: Path: /Cats Method: ANY getBirdsFunction: Type: AWS::Serverless::Function Properties: Handler: getBirds.handler Timeout: 15 Events: GetBirds: Type: Api Properties: Path: /Birds Method: ANY AWS SAM Globals
  32. 32. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM Policy Templates MyQueueFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Gives permissions to poll an SQS Queue - SQSPollerPolicy: queueName: !Ref MyQueue ... MyQueue: Type: AWS::SQS::Queue
  33. 33. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved SAM Policy Templates 45+ predefined policies All found here: https://bit.ly/2xWycnj
  34. 34. Beyond the Template
  35. 35. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM Command Line Interface (AWS SAM CLI) CLI tool for local development, debugging, testing, deploying, and monitoring of serverless applications Supports API Gateway “proxy-style” and Lambda service API testing Response object and function logs available on your local machine Uses open source docker-lambda images to mimic Lambda’s execution environment such as timeout, memory limits, runtimes Can tail production logs from CloudWatch logs Can help you build in native dependencies https://aws.amazon.com/serverless/sam NEW!
  36. 36. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved AWS SAM CLI - Commands • build: Install dependencies • deploy: Deploy an AWS SAM application. This is an alias for ‘aws cloudformation deploy’ • init: Initialize a serverless application • local: – generate-event: You can use this command to generate sample payloads from different event sources – invoke: Invokes a local Lambda function once – start-api: Sets up a local endpoint you can use to test your API – start-lambda: Starts a local endpoint you can use to invoke your local Lambda functions • logs: Fetch logs for a function • package: Package an AWS SAM application. This is an alias for ‘aws cloudformation package' • publish: Publish a packaged AWS SAM template to the AWS Serverless Application Repository • validate: Validate an AWS SAM template
  37. 37. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved
  38. 38. DEMO!
  39. 39. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved SAM Translator • In 2018 rewritten and open sourced! • Python based • PRs get merged into SAM and then Lambda team will refresh the translator service periodically • Integration back to SAM CLI means SAM CLI keeps up to date more easily now • What other resources can be SAM-ified?
  40. 40. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved SAM Translator
  41. 41. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved
  42. 42. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved With the AWS Serverless Application Repository: Developers can… • Discover and deploy ready-made apps and code samples • Combine applications in the app repository with their own via Nested Applications (NEW) • Customize open-source apps to get started quickly • Share apps privately or publish apps for public use
  43. 43. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Launched via AWS Serverless Application Repository parent relationship ”nested” Serverless Application Stack ”root” Serverless Application Stack ”nested” Serverless Application Stack ”nested” Serverless Application Stack
  44. 44. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved DEMO!
  45. 45. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved aws.amazon.com/serverless/sam
  46. 46. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved aws.amazon.com/serverless
  47. 47. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved Chris Munns munns@amazon.com @chrismunnshttps://www.flickr.com/photos/theredproject/3302110152/
  48. 48. © 2019, Amazon Web Services, Inc. or its Affiliates. All rights reserved ? https://secure.flickr.com/photos/dullhunk/202872717/

×