SlideShare uma empresa Scribd logo
1 de 61
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Chris Munns – Senior Developer Advocate - Serverless
Serverless Applications
with AWS SAM
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
About me:
Chris Munns - munns@amazon.com, @chrismunns
• Senior 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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
https://secure.flickr.com/photos/mgifford/4525333972
Why are we
here today?
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
No servers to provision
or manage
Scales with usage
Never pay for idle Availability and fault
tolerance built in
Serverless means…
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SERVICES (ANYTHING)
Changes in
data state
Requests to
endpoints
Changes in
resource state
EVENT SOURCE FUNCTION
Node.js
Python
Java
C#
Go
Serverless applications
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Handler() function
Function to be executed
upon invocation
Event object
Data sent during
Lambda Function
Invocation
Context object
Methods available to
interact with runtime
information (request ID,
log group, etc.)
public String handleRequest(Book book, Context context) {
saveBook(book);
return book.getName() + " saved!";
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda permissions model
Fine grained security controls for both
execution and invocation:
Execution policies:
• Define what AWS resources/API calls can this
function access via IAM
• Used in streaming invocations
• E.g. “Lambda function A can read from
DynamoDB table users”
Function policies:
• Used for sync and async invocations
• E.g. “Actions on bucket X can invoke Lambda
function Z"
• Resource policies allow for cross account
access
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda execution model
Synchronous
(push)
Asynchronous
(event)
Stream-based
Amazon
API Gateway
AWS Lambda
function
Amazon
DynamoDBAmazon
SNS
/order
AWS Lambda
function
Amazon
S3
reqs
Amazon
Kinesis
changes
AWS Lambda
service
function
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Amazon S3 Amazon
DynamoDB
Amazon
Kinesis
AWS
CloudFormation
AWS CloudTrail Amazon
CloudWatch
Amazon
Cognito
Amazon SNSAmazon
SES
Cron events
DATA STORES ENDPOINTS
DEVELOPMENT AND MANAGEMENT TOOLS EVENT/MESSAGE SERVICES
Event sources that trigger AWS Lambda
and more!
AWS
CodeCommit
Amazon
API Gateway
Amazon
Alexa
AWS IoT AWS Step
Functions
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Common Lambda use cases
Web
Applications
• Static
websites
• Complex web
apps
• Packages for
Flask and
Express
Data
Processing
• Real time
• MapReduce
• Batch
Chatbots
• Powering
chatbot logic
Backends
• Apps &
services
• Mobile
• IoT
</></>
Amazon
Alexa
• Powering
voice-enabled
apps
• Alexa Skills
Kit
IT
Automation
• Policy engines
• Extending
AWS services
• Infrastructure
management
Meet
SAM!
AWS Serverless Application Model (SAM)
CloudFormation extension optimized for
serverless
New serverless resource types: functions, APIs,
and tables
Supports anything CloudFormation supports
Open specification (Apache 2.0)
- SAM Translator recently open sourced!
https://github.com/awslabs/serverless-application-model
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Create templates of your infrastructure
CloudFormation provisions AWS resources
based on dependency needs
Version control/replicate/update templates like
code
Integrates with development, CI/CD,
management tools
JSON and YAML supported
AWS CloudFormation
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormation template
AWSTemplateFormatVersion: '2010-09-09'
Resources:
GetHtmlFunctionGetHtmlPermissionProd:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: apigateway.amazonaws.com
FunctionName:
Ref: GetHtmlFunction
SourceArn:
Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/Prod/ANY/*
ServerlessRestApiProdStage:
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId:
Ref: ServerlessRestApiDeployment
RestApiId:
Ref: ServerlessRestApi
StageName: Prod
ListTable:
Type: AWS::DynamoDB::Table
Properties:
ProvisionedThroughput:
WriteCapacityUnits: 5
ReadCapacityUnits: 5
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- KeyType: HASH
AttributeName: id
GetHtmlFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.gethtml
Code:
S3Bucket: flourish-demo-bucket
S3Key: todo_list.zip
Role:
Fn::GetAtt:
- GetHtmlFunctionRole
- Arn
Runtime: nodejs4.3
GetHtmlFunctionRole:
Type: AWS::IAM::Role
Properties:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ServerlessRestApiDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId:
Ref: ServerlessRestApi
Description: 'RestApi deployment id: 127e3fb91142ab1ddc5f5446adb094442581a90d'
StageName: Stage
GetHtmlFunctionGetHtmlPermissionTest:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: apigateway.amazonaws.com
FunctionName:
Ref: GetHtmlFunction
SourceArn:
Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/ANY/*
ServerlessRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Body:
info:
version: '1.0'
title:
Ref: AWS::StackName
paths:
"/{proxy+}":
x-amazon-apigateway-any-method:
x-amazon-apigateway-integration:
httpMethod: ANY
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-
31/functions/${GetHtmlFunction.Arn}/invocations
responses: {}
swagger: '2.0'
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWSTemplateFormatVersion: '2010-09-09'
Resources:
GetHtmlFunctionGetHtmlPermissionProd:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: apigateway.amazonaws.com
FunctionName:
Ref: GetHtmlFunction
SourceArn:
Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/Prod/ANY/*
ServerlessRestApiProdStage:
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId:
Ref: ServerlessRestApiDeployment
RestApiId:
Ref: ServerlessRestApi
StageName: Prod
ListTable:
Type: AWS::DynamoDB::Table
Properties:
ProvisionedThroughput:
WriteCapacityUnits: 5
ReadCapacityUnits: 5
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- KeyType: HASH
AttributeName: id
GetHtmlFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.gethtml
Code:
S3Bucket: flourish-demo-bucket
S3Key: todo_list.zip
Role:
Fn::GetAtt:
- GetHtmlFunctionRole
- Arn
Runtime: nodejs4.3
GetHtmlFunctionRole:
Type: AWS::IAM::Role
Properties:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ServerlessRestApiDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId:
Ref: ServerlessRestApi
Description: 'RestApi deployment id: 127e3fb91142ab1ddc5f5446adb094442581a90d'
StageName: Stage
GetHtmlFunctionGetHtmlPermissionTest:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:invokeFunction
Principal: apigateway.amazonaws.com
FunctionName:
Ref: GetHtmlFunction
SourceArn:
Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/ANY/*
ServerlessRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Body:
info:
version: '1.0'
title:
Ref: AWS::StackName
paths:
"/{proxy+}":
x-amazon-apigateway-any-method:
x-amazon-apigateway-integration:
httpMethod: ANY
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-
31/functions/${GetHtmlFunction.Arn}/invocations
responses: {}
swagger: '2.0'
CloudFormation template
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: nodejs4.3
Policies: AmazonDynamoDBReadOnlyAccess
Events:
GetHtml:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
ListTable:
Type: AWS::Serverless::SimpleTable
SAM Template
Tells CloudFormation this is a SAM
template it needs to “transform”
Creates a Lambda function with the
referenced managed IAM policy,
runtime, code at the referenced zip
location, and handler as defined.
Also creates an API Gateway and
takes care of all
mapping/permissions necessary
Creates a 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: nodejs4.3
Policies: AmazonDynamoDBReadOnlyAccess
Events:
GetHtml:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
ListTable:
Type: AWS::Serverless::SimpleTable
From: https://github.com/awslabs/aws-serverless-samfarm/blob/master/api/saml.yaml
<-THIS
BECOMES THIS->
SAM Template
SAM Template Properties
AWS::Serverless::Function
AWS::Serverless::Api
AWS::Serverless::SimpleTable
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
SAM Template Properties
AWS::Serverless::Function
AWS::Serverless::Api
AWS::Serverless::SimpleTable
StageName: prod
DefinitionUri: swagger.yml
CacheClusterEnabled: true
CacheClusterSize: 28.4
Variables:
VarName: VarValue
From SAM Version 2016-10-31
SAM Template Properties
AWS::Serverless::Function
AWS::Serverless::Api
AWS::Serverless::SimpleTable
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
From SAM Version 2016-10-31
AWS::Serverless::Function Event source types
From SAM Version 2016-10-31
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
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
Type: S3
Properties:
Bucket: bucket-name*
Events: S3:Supported events**
Filter:
S3Key:
Rules:
-
Name: prefix|suffix
Value: String
-
Name: prefix|suffix
Value: String
*Bucket must be declared in same template today
**https://docs.aws.amazon.com/AmazonS3/latest/dev/Not
ificationHowTo.html#supported-notification-event-
typesFrom SAM Version 2016-10-31
AWS::Serverless::Function Event source types
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
Type: SNS
Properties:
Topic: arn:aws:sns:<region>:<account-
id>:topic_name
From SAM Version 2016-10-31
AWS::Serverless::Function Event source types
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
Type: Kinesis
Properties:
Stream:
arn:aws:kinesis:<region>:<account-
id>:stream/stream_name
StartingPosition: TRIM_HORIZON|LATEST
BatchSize: <integer>
--------------------------------
Type: DynamoDB
Properties:
Stream:
arn:aws:dynamodb:<region>:<account-
id>:table/table_name/stream/<time stamp>
StartingPosition: TRIM_HORIZON|LATEST
BatchSize: <integer>
From SAM Version 2016-10-31
AWS::Serverless::Function Event source types
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
Type: Schedule
Properties:
Schedule: Cron|Rate Expression
Input: JSON formatted string
Cron examples:
cron(* * * * * *) (every minute)
cron(1/5 8-17 * * 2-6 *) (every five
minutes, between 8am and 5pm, Monday-
Friday)
Rate Expression examples:
rate(10 minutes)
rate(1 hour)
From SAM Version 2016-10-31
AWS::Serverless::Function Event source types
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
Type: CloudWatchEvent
Properties:
Pattern: CWE Pattern*
Input: JSON formatted string that
overrides the matched event
Inputpath: JSONPath describing part
of the event to pass forward
*https://docs.aws.amazon.com/AmazonCloudWatch/latest/event
s/CloudWatchEventsandEventPatterns.html
From SAM Version 2016-10-31
AWS::Serverless::Function Event source types
S3
SNS
Kinesis | DynamoDB
Api
Schedule
CloudWatchEvent
IoTRule
AlexaSkill
Type: AlexaSkill*
* creates a resource policy that allows the Amazon
Alexa service to call your Lambda function
powers:
From SAM Version 2016-10-31
AWS SAM CLI SAM Local
Relaunched/GA’d on May 8th!
CLI tool for local building, validating, testing of
serverless apps
Works with Lambda functions and “proxy-style”
APIs
Response object and function logs available on
your local machine
Uses open source docker-lambda images to mimic
Lambda’s execution environment:
• Emulates timeout, memory limits, runtimes
https://github.com/awslabs/aws-sam-cli
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Local CLI
$ sam --help
Usage: sam [OPTIONS] COMMAND [ARGS]...
AWS Serverless Application Model (SAM) CLI
The AWS Serverless Application Model extends AWS CloudFormation to provide
a simplified way of defining the Amazon API Gateway APIs, AWS Lambda
functions, and Amazon DynamoDB tables needed by your serverless
application. You can find more in-depth guide about the SAM specification
here: https://github.com/awslabs/serverless-application-model.
Options:
--debug Turn on debug logging
--version Show the version and exit.
--help Show this message and exit.
Commands:
init Initialize a serverless application with a...
package Package an AWS SAM application. This is an alias for 'aws
cloudformation package'.
local Run your Serverless application locally for...
validate Validate an AWS SAM template.
deploy Deploy an AWS SAM application. This is an alias for 'aws
cloudformation deploy'.
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Local CLI
$ sam --help
Usage: sam [OPTIONS] COMMAND [ARGS]...
AWS Serverless Application Model (SAM) CLI
The AWS Serverless Application Model extends AWS CloudFormation to provide
a simplified way of defining the Amazon API Gateway APIs, AWS Lambda
functions, and Amazon DynamoDB tables needed by your serverless
application. You can find more in-depth guide about the SAM specification
here: https://github.com/awslabs/serverless-application-model.
Options:
--debug Turn on debug logging
--version Show the version and exit.
--help Show this message and exit.
Commands:
init Initialize a serverless application with a...
package Package an AWS SAM application. This is an alias for 'aws
cloudformation package'.
local Run your Serverless application locally for...
validate Validate an AWS SAM template.
deploy Deploy an AWS SAM application. This is an alias for 'aws
cloudformation deploy'.
DEMO!
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Cloud9
© 2018, 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" ] }
}
}
}
{
"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
{
"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
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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
Templates (in action):
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" },
{"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
Templates (in action):
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" },
{"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
“AWSRegionVirt2AMI” Map
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
Templates (in action):
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" },
{"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
“AWSRegionVirt2AMI” Map
“AWSInstanceType2Virt” Map
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
Templates (in action):
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" },
{"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
“AWSRegionVirt2AMI” Map
“AWSInstanceType2Virt” Map
“myInstanceType”
Parameter
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
Templates (in action):
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" },
{"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
“AWSRegionVirt2AMI” Map
“AWSInstanceType2Virt” Map
“myInstanceType”
Parameter
AWS::Region Pseudo
Parameter
AWS CloudFormation
Parameters:
"myInstanceType" : {
"Type" : "String",
"Default" : "t2.large",
"AllowedValues" : ["t2.micro", "t2.small", "t2.medium", "t2.large"],
"Description" : "Instance type for instances created, must be in the
t2 family."
}
Mappings:
"AWSInstanceType2Virt": {
"t2.micro": {"Virt": "HVM"},
"t2.small": {"Virt": "HVM"},
"t2.medium": {"Virt": "HVM"},
"t2.large": {"Virt": "HVM"},
}
Mappings:
"AWSRegionVirt2AMI": {
"us-east-1": {
"PVM": "ami-50842d38",
"HVM": "ami-08842d60"
},
"us-west-2": {
"PVM": "ami-af86c69f",
"HVM": "ami-8786c6b7"
},
"us-west-1": {
"PVM": "ami-c7a8a182",
"HVM": "ami-cfa8a18a"
}
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Template Capabilities
• Can mix in other non-SAM CloudFormation
resources in the same template
• i.e. S3, Kinesis, Step Functions
• Supports use of Parameters, Mappings,
Outputs, etc
• Supports Intrinsic Functions
• Can use ImportValue
(exceptions for RestApiId, Policies, StageName attributes)
• YAML or JSON
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
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)
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda and API Gateway Variables + SAM
Parameters:
MyEnvironment:
Type: String
Default: testing
AllowedValues:
- testing
- staging
- prod
Description: Environment of this stack of
resources
SpecialFeature1:
Type: String
Default: false
AllowedValues:
- true
- false
Description: Enable new SpecialFeature1
…
#Lambda
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
…
Environment:
Variables:
ENVIRONMENT: !Ref: MyEnvironment
Spec_Feature1: !Ref: SpecialFeature1
…
#API Gateway
MyApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
…
Variables:
ENVIRONMENT: !Ref: MyEnvironment
SPEC_Feature1: !Ref: SpecialFeature1
…
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM + Safe Deployments
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs4.3
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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM + Safe Deployments
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs4.3
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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
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:
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
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
In SAM:
Note: You can specify a maximum of 10 alarms
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Globals
Globals:
Function:
Runtime: nodejs4.3
CodeUri: s3://sam-demo-bucket/todo_list.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
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Policy Templates
MyFunction:
Type: AWS::Serverless::Function
Properties:
...
Policies:
# Give just CRUD permissions to one table
- DynamoDBCrudPolicy:
TableName: !Ref MyTable
...
MyTable:
Type: AWS::Serverless::SimpleTable
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Policy Templates
MyFunction:
Type: AWS::Serverless::Function
Properties:
...
Policies:
# Give just CRUD permissions to one table
- DynamoDBCrudPolicy:
TableName: !Ref MyTable
...
MyTable:
Type: AWS::Serverless::SimpleTable
All found here:
https://github.com/awslabs/serverless-
application-
model/blob/develop/docs/policy_templates
_data/policy_templates.json
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Best
Practices
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SAM Best Practices
• Use Parameters and Mappings when possible to build
dynamic templates based on user inputs and pseudo
parameters such as AWS::Region
• Use the Globals section to simplify templates
• Use ExportValue & ImportValue to share resource
information across stacks
• Build out multiple environments, such as for
Development, Test, Production and even DR using the
same template, even across accounts
SAM Template
Source
Control
Dev
Test
Prod
SAM Best Practices
• Unless function handlers share code, split them into their
own independent Lambda functions files or binaries
• Another option is to use language specific packages to share
common code between functions
• Unless independent Lambda functions share event
sources, split them into their own code repositories with
their own SAM templates
• Locally lint your YAML or JSON SAM files before
committing them. Then do it again in your CI/CD process
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
A serverless application delivery pipeline:
This pipeline:
• Five Stages
• Builds code artifact
• Three deployed to “Environments”
• Uses SAM/CloudFormation to
deploy artifact and other AWS
resources
• Has Lambda custom actions for
running my own testing functions
• Integrates with a 3rd party
tool/service
• Has a manual approval before
deploying to production
• Creates a client SDK at the end
Source
Source
CodeCommit
MyApplication
Build
test-build-source
CodeBuild
Deploy Testing
create-changeset
AWS
CloudFormation
execute-changeset
AWS
CloudFormation
Run-stubs
AWS Lambda
Deploy Staging
create-changeset
AWS
CloudFormation
execute-changeset
AWS
CloudFormation
Run-API-test
Runscope
QA-Sign-off
Manual Approval
Review
Deploy Prod
create-changeset
AWS
CloudFormation
execute-changeset
AWS
CloudFormation
Create SDK
AWS Lambda
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
aws.amazon.com/serverless
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Chris Munns
munns@amazon.com
@chrismunnshttps://www.flickr.com/photos/theredproject/3302110152/
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
https://secure.flickr.com/photos/dullhunk/202872717/

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Building serverless applications with Amazon S3
Building serverless applications with Amazon S3Building serverless applications with Amazon S3
Building serverless applications with Amazon S3
 
muCon 2017 - 12 Factor Serverless Applications
muCon 2017 - 12 Factor Serverless ApplicationsmuCon 2017 - 12 Factor Serverless Applications
muCon 2017 - 12 Factor Serverless Applications
 
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
 
AWS Lambda Layers, the Runtime API, & Nested Applications: re:Invent 2018 Rec...
AWS Lambda Layers, the Runtime API, & Nested Applications: re:Invent 2018 Rec...AWS Lambda Layers, the Runtime API, & Nested Applications: re:Invent 2018 Rec...
AWS Lambda Layers, the Runtime API, & Nested Applications: re:Invent 2018 Rec...
 
Lambda Layers & Runtime API
Lambda Layers & Runtime APILambda Layers & Runtime API
Lambda Layers & Runtime API
 
Serverless and DevOps
Serverless and DevOpsServerless and DevOps
Serverless and DevOps
 
Build and Deploy Serverless Applications with AWS SAM
Build and Deploy Serverless Applications with AWS SAM Build and Deploy Serverless Applications with AWS SAM
Build and Deploy Serverless Applications with AWS SAM
 
All the Ops you need to know to Dev Serverless
All the Ops you need to know to Dev ServerlessAll the Ops you need to know to Dev Serverless
All the Ops you need to know to Dev Serverless
 
Building APIs with Amazon API Gateway: re:Invent 2018 Recap at the AWS Loft -...
Building APIs with Amazon API Gateway: re:Invent 2018 Recap at the AWS Loft -...Building APIs with Amazon API Gateway: re:Invent 2018 Recap at the AWS Loft -...
Building APIs with Amazon API Gateway: re:Invent 2018 Recap at the AWS Loft -...
 
Overview of Serverless Application Deployment Patterns - AWS Online Tech Talks
Overview of Serverless Application Deployment Patterns - AWS Online Tech TalksOverview of Serverless Application Deployment Patterns - AWS Online Tech Talks
Overview of Serverless Application Deployment Patterns - AWS Online Tech Talks
 
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
 
Introduction to Serverless computing and AWS Lambda - Floor28
Introduction to Serverless computing and AWS Lambda - Floor28Introduction to Serverless computing and AWS Lambda - Floor28
Introduction to Serverless computing and AWS Lambda - Floor28
 
Authoring and Deploying Serverless Applications with AWS SAM
Authoring and Deploying Serverless Applications with AWS SAMAuthoring and Deploying Serverless Applications with AWS SAM
Authoring and Deploying Serverless Applications with AWS SAM
 
re:Invent 2018: AI/ML Services
re:Invent 2018: AI/ML Servicesre:Invent 2018: AI/ML Services
re:Invent 2018: AI/ML Services
 
How AWS builds Serverless services using Serverless
How AWS builds Serverless services using ServerlessHow AWS builds Serverless services using Serverless
How AWS builds Serverless services using Serverless
 
Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep Dive
 
Deep Dive on Serverless Application Development
Deep Dive on Serverless Application DevelopmentDeep Dive on Serverless Application Development
Deep Dive on Serverless Application Development
 
Getting Started with AWS Lambda Serverless Computing
Getting Started with AWS Lambda Serverless ComputingGetting Started with AWS Lambda Serverless Computing
Getting Started with AWS Lambda Serverless Computing
 
Getting Started with AWS Lambda and Serverless Computing
Getting Started with AWS Lambda and Serverless ComputingGetting Started with AWS Lambda and Serverless Computing
Getting Started with AWS Lambda and Serverless Computing
 
Deep Dive on Amazon Elastic Container Service (ECS) I AWS Dev Day 2018
Deep Dive on Amazon Elastic Container Service (ECS) I AWS Dev Day 2018Deep Dive on Amazon Elastic Container Service (ECS) I AWS Dev Day 2018
Deep Dive on Amazon Elastic Container Service (ECS) I AWS Dev Day 2018
 

Semelhante a Serverless Applications with AWS SAM

Semelhante a Serverless Applications with AWS SAM (20)

Serverless Developer Experience I AWS Dev Day 2018
Serverless Developer Experience I AWS Dev Day 2018Serverless Developer Experience I AWS Dev Day 2018
Serverless Developer Experience I AWS Dev Day 2018
 
Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep Dive
 
Building CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless ApplicationsBuilding CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless Applications
 
Getting Started with AWS Lambda & Serverless Computing
Getting Started with AWS Lambda & Serverless ComputingGetting Started with AWS Lambda & Serverless Computing
Getting Started with AWS Lambda & Serverless Computing
 
SMC305 Building CI/CD Pipelines for Serverless Applications
SMC305 Building CI/CD Pipelines for Serverless ApplicationsSMC305 Building CI/CD Pipelines for Serverless Applications
SMC305 Building CI/CD Pipelines for Serverless Applications
 
Build Enterprise-Grade Serverless Apps - SRV315 - Atlanta AWS Summit
Build Enterprise-Grade Serverless Apps - SRV315 - Atlanta AWS SummitBuild Enterprise-Grade Serverless Apps - SRV315 - Atlanta AWS Summit
Build Enterprise-Grade Serverless Apps - SRV315 - Atlanta AWS Summit
 
Application Lifecycle Management in a Serverless World | AWS Public Sector Su...
Application Lifecycle Management in a Serverless World | AWS Public Sector Su...Application Lifecycle Management in a Serverless World | AWS Public Sector Su...
Application Lifecycle Management in a Serverless World | AWS Public Sector Su...
 
Building AWS Lambda Applications with the AWS Serverless Application Model (A...
Building AWS Lambda Applications with the AWS Serverless Application Model (A...Building AWS Lambda Applications with the AWS Serverless Application Model (A...
Building AWS Lambda Applications with the AWS Serverless Application Model (A...
 
Building serverless enterprise applications - SRV315 - Toronto AWS Summit
Building serverless enterprise applications - SRV315 - Toronto AWS SummitBuilding serverless enterprise applications - SRV315 - Toronto AWS Summit
Building serverless enterprise applications - SRV315 - Toronto AWS Summit
 
Deep Dive on Serverless App Development
Deep Dive on Serverless App DevelopmentDeep Dive on Serverless App Development
Deep Dive on Serverless App Development
 
Deep Dive On Serverless App Development
Deep Dive On Serverless App DevelopmentDeep Dive On Serverless App Development
Deep Dive On Serverless App Development
 
Build Enterprise-Grade Serverless Apps - SRV315 - Chicago AWS Summit
Build Enterprise-Grade Serverless Apps - SRV315 - Chicago AWS SummitBuild Enterprise-Grade Serverless Apps - SRV315 - Chicago AWS Summit
Build Enterprise-Grade Serverless Apps - SRV315 - Chicago AWS Summit
 
Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps
 
Serverless computing - Build and run applications without thinking about servers
Serverless computing - Build and run applications without thinking about serversServerless computing - Build and run applications without thinking about servers
Serverless computing - Build and run applications without thinking about servers
 
The Future of Enterprise Applications is Serverless (ENT314-R1) - AWS re:Inve...
The Future of Enterprise Applications is Serverless (ENT314-R1) - AWS re:Inve...The Future of Enterprise Applications is Serverless (ENT314-R1) - AWS re:Inve...
The Future of Enterprise Applications is Serverless (ENT314-R1) - AWS re:Inve...
 
Building API Driven Microservices
Building API Driven MicroservicesBuilding API Driven Microservices
Building API Driven Microservices
 
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
 
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
 
Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep Dive
 
Building Serverless Enterprise Applications - SRV315 - Anaheim AWS Summit
Building Serverless Enterprise Applications - SRV315 - Anaheim AWS SummitBuilding Serverless Enterprise Applications - SRV315 - Anaheim AWS Summit
Building Serverless Enterprise Applications - SRV315 - Anaheim AWS Summit
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Serverless Applications with AWS SAM

  • 1. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Chris Munns – Senior Developer Advocate - Serverless Serverless Applications with AWS SAM
  • 2. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. About me: Chris Munns - munns@amazon.com, @chrismunns • Senior 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. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. https://secure.flickr.com/photos/mgifford/4525333972 Why are we here today?
  • 4. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. No servers to provision or manage Scales with usage Never pay for idle Availability and fault tolerance built in Serverless means…
  • 5. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SERVICES (ANYTHING) Changes in data state Requests to endpoints Changes in resource state EVENT SOURCE FUNCTION Node.js Python Java C# Go Serverless applications
  • 6. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Handler() function Function to be executed upon invocation Event object Data sent during Lambda Function Invocation Context object Methods available to interact with runtime information (request ID, log group, etc.) public String handleRequest(Book book, Context context) { saveBook(book); return book.getName() + " saved!"; }
  • 7. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda permissions model Fine grained security controls for both execution and invocation: Execution policies: • Define what AWS resources/API calls can this function access via IAM • Used in streaming invocations • E.g. “Lambda function A can read from DynamoDB table users” Function policies: • Used for sync and async invocations • E.g. “Actions on bucket X can invoke Lambda function Z" • Resource policies allow for cross account access
  • 8. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda execution model Synchronous (push) Asynchronous (event) Stream-based Amazon API Gateway AWS Lambda function Amazon DynamoDBAmazon SNS /order AWS Lambda function Amazon S3 reqs Amazon Kinesis changes AWS Lambda service function
  • 9. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Amazon S3 Amazon DynamoDB Amazon Kinesis AWS CloudFormation AWS CloudTrail Amazon CloudWatch Amazon Cognito Amazon SNSAmazon SES Cron events DATA STORES ENDPOINTS DEVELOPMENT AND MANAGEMENT TOOLS EVENT/MESSAGE SERVICES Event sources that trigger AWS Lambda and more! AWS CodeCommit Amazon API Gateway Amazon Alexa AWS IoT AWS Step Functions
  • 10. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Common Lambda use cases Web Applications • Static websites • Complex web apps • Packages for Flask and Express Data Processing • Real time • MapReduce • Batch Chatbots • Powering chatbot logic Backends • Apps & services • Mobile • IoT </></> Amazon Alexa • Powering voice-enabled apps • Alexa Skills Kit IT Automation • Policy engines • Extending AWS services • Infrastructure management
  • 12. AWS Serverless Application Model (SAM) CloudFormation extension optimized for serverless New serverless resource types: functions, APIs, and tables Supports anything CloudFormation supports Open specification (Apache 2.0) - SAM Translator recently open sourced! https://github.com/awslabs/serverless-application-model
  • 13. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Create templates of your infrastructure CloudFormation provisions AWS resources based on dependency needs Version control/replicate/update templates like code Integrates with development, CI/CD, management tools JSON and YAML supported AWS CloudFormation
  • 14. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. CloudFormation template AWSTemplateFormatVersion: '2010-09-09' Resources: GetHtmlFunctionGetHtmlPermissionProd: Type: AWS::Lambda::Permission Properties: Action: lambda:invokeFunction Principal: apigateway.amazonaws.com FunctionName: Ref: GetHtmlFunction SourceArn: Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/Prod/ANY/* ServerlessRestApiProdStage: Type: AWS::ApiGateway::Stage Properties: DeploymentId: Ref: ServerlessRestApiDeployment RestApiId: Ref: ServerlessRestApi StageName: Prod ListTable: Type: AWS::DynamoDB::Table Properties: ProvisionedThroughput: WriteCapacityUnits: 5 ReadCapacityUnits: 5 AttributeDefinitions: - AttributeName: id AttributeType: S KeySchema: - KeyType: HASH AttributeName: id GetHtmlFunction: Type: AWS::Lambda::Function Properties: Handler: index.gethtml Code: S3Bucket: flourish-demo-bucket S3Key: todo_list.zip Role: Fn::GetAtt: - GetHtmlFunctionRole - Arn Runtime: nodejs4.3 GetHtmlFunctionRole: Type: AWS::IAM::Role Properties: ManagedPolicyArns: - arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Action: - sts:AssumeRole Effect: Allow Principal: Service: - lambda.amazonaws.com ServerlessRestApiDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: Ref: ServerlessRestApi Description: 'RestApi deployment id: 127e3fb91142ab1ddc5f5446adb094442581a90d' StageName: Stage GetHtmlFunctionGetHtmlPermissionTest: Type: AWS::Lambda::Permission Properties: Action: lambda:invokeFunction Principal: apigateway.amazonaws.com FunctionName: Ref: GetHtmlFunction SourceArn: Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/ANY/* ServerlessRestApi: Type: AWS::ApiGateway::RestApi Properties: Body: info: version: '1.0' title: Ref: AWS::StackName paths: "/{proxy+}": x-amazon-apigateway-any-method: x-amazon-apigateway-integration: httpMethod: ANY type: aws_proxy uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03- 31/functions/${GetHtmlFunction.Arn}/invocations responses: {} swagger: '2.0'
  • 15. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWSTemplateFormatVersion: '2010-09-09' Resources: GetHtmlFunctionGetHtmlPermissionProd: Type: AWS::Lambda::Permission Properties: Action: lambda:invokeFunction Principal: apigateway.amazonaws.com FunctionName: Ref: GetHtmlFunction SourceArn: Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/Prod/ANY/* ServerlessRestApiProdStage: Type: AWS::ApiGateway::Stage Properties: DeploymentId: Ref: ServerlessRestApiDeployment RestApiId: Ref: ServerlessRestApi StageName: Prod ListTable: Type: AWS::DynamoDB::Table Properties: ProvisionedThroughput: WriteCapacityUnits: 5 ReadCapacityUnits: 5 AttributeDefinitions: - AttributeName: id AttributeType: S KeySchema: - KeyType: HASH AttributeName: id GetHtmlFunction: Type: AWS::Lambda::Function Properties: Handler: index.gethtml Code: S3Bucket: flourish-demo-bucket S3Key: todo_list.zip Role: Fn::GetAtt: - GetHtmlFunctionRole - Arn Runtime: nodejs4.3 GetHtmlFunctionRole: Type: AWS::IAM::Role Properties: ManagedPolicyArns: - arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Action: - sts:AssumeRole Effect: Allow Principal: Service: - lambda.amazonaws.com ServerlessRestApiDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: Ref: ServerlessRestApi Description: 'RestApi deployment id: 127e3fb91142ab1ddc5f5446adb094442581a90d' StageName: Stage GetHtmlFunctionGetHtmlPermissionTest: Type: AWS::Lambda::Permission Properties: Action: lambda:invokeFunction Principal: apigateway.amazonaws.com FunctionName: Ref: GetHtmlFunction SourceArn: Fn::Sub: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ServerlessRestApi}/*/ANY/* ServerlessRestApi: Type: AWS::ApiGateway::RestApi Properties: Body: info: version: '1.0' title: Ref: AWS::StackName paths: "/{proxy+}": x-amazon-apigateway-any-method: x-amazon-apigateway-integration: httpMethod: ANY type: aws_proxy uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03- 31/functions/${GetHtmlFunction.Arn}/invocations responses: {} swagger: '2.0' CloudFormation template
  • 16. 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: nodejs4.3 Policies: AmazonDynamoDBReadOnlyAccess Events: GetHtml: Type: Api Properties: Path: /{proxy+} Method: ANY ListTable: Type: AWS::Serverless::SimpleTable
  • 17. SAM Template Tells CloudFormation this is a SAM template it needs to “transform” Creates a Lambda function with the referenced managed IAM policy, runtime, code at the referenced zip location, and handler as defined. Also creates an API Gateway and takes care of all mapping/permissions necessary Creates a 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: nodejs4.3 Policies: AmazonDynamoDBReadOnlyAccess Events: GetHtml: Type: Api Properties: Path: /{proxy+} Method: ANY ListTable: Type: AWS::Serverless::SimpleTable
  • 19. SAM Template Properties AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable 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
  • 20. SAM Template Properties AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable StageName: prod DefinitionUri: swagger.yml CacheClusterEnabled: true CacheClusterSize: 28.4 Variables: VarName: VarValue From SAM Version 2016-10-31
  • 21. SAM Template Properties AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable PrimaryKey: Name: id Type: String ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 From SAM Version 2016-10-31
  • 22. AWS::Serverless::Function Event source types From SAM Version 2016-10-31 S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill 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
  • 23. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: S3 Properties: Bucket: bucket-name* Events: S3:Supported events** Filter: S3Key: Rules: - Name: prefix|suffix Value: String - Name: prefix|suffix Value: String *Bucket must be declared in same template today **https://docs.aws.amazon.com/AmazonS3/latest/dev/Not ificationHowTo.html#supported-notification-event- typesFrom SAM Version 2016-10-31
  • 24. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: SNS Properties: Topic: arn:aws:sns:<region>:<account- id>:topic_name From SAM Version 2016-10-31
  • 25. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: Kinesis Properties: Stream: arn:aws:kinesis:<region>:<account- id>:stream/stream_name StartingPosition: TRIM_HORIZON|LATEST BatchSize: <integer> -------------------------------- Type: DynamoDB Properties: Stream: arn:aws:dynamodb:<region>:<account- id>:table/table_name/stream/<time stamp> StartingPosition: TRIM_HORIZON|LATEST BatchSize: <integer> From SAM Version 2016-10-31
  • 26. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: Schedule Properties: Schedule: Cron|Rate Expression Input: JSON formatted string Cron examples: cron(* * * * * *) (every minute) cron(1/5 8-17 * * 2-6 *) (every five minutes, between 8am and 5pm, Monday- Friday) Rate Expression examples: rate(10 minutes) rate(1 hour) From SAM Version 2016-10-31
  • 27. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: CloudWatchEvent Properties: Pattern: CWE Pattern* Input: JSON formatted string that overrides the matched event Inputpath: JSONPath describing part of the event to pass forward *https://docs.aws.amazon.com/AmazonCloudWatch/latest/event s/CloudWatchEventsandEventPatterns.html From SAM Version 2016-10-31
  • 28. AWS::Serverless::Function Event source types S3 SNS Kinesis | DynamoDB Api Schedule CloudWatchEvent IoTRule AlexaSkill Type: AlexaSkill* * creates a resource policy that allows the Amazon Alexa service to call your Lambda function powers: From SAM Version 2016-10-31
  • 29. AWS SAM CLI SAM Local Relaunched/GA’d on May 8th! CLI tool for local building, validating, testing of serverless apps Works with Lambda functions and “proxy-style” APIs Response object and function logs available on your local machine Uses open source docker-lambda images to mimic Lambda’s execution environment: • Emulates timeout, memory limits, runtimes https://github.com/awslabs/aws-sam-cli
  • 30. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Local CLI $ sam --help Usage: sam [OPTIONS] COMMAND [ARGS]... AWS Serverless Application Model (SAM) CLI The AWS Serverless Application Model extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application. You can find more in-depth guide about the SAM specification here: https://github.com/awslabs/serverless-application-model. Options: --debug Turn on debug logging --version Show the version and exit. --help Show this message and exit. Commands: init Initialize a serverless application with a... package Package an AWS SAM application. This is an alias for 'aws cloudformation package'. local Run your Serverless application locally for... validate Validate an AWS SAM template. deploy Deploy an AWS SAM application. This is an alias for 'aws cloudformation deploy'.
  • 31. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Local CLI $ sam --help Usage: sam [OPTIONS] COMMAND [ARGS]... AWS Serverless Application Model (SAM) CLI The AWS Serverless Application Model extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application. You can find more in-depth guide about the SAM specification here: https://github.com/awslabs/serverless-application-model. Options: --debug Turn on debug logging --version Show the version and exit. --help Show this message and exit. Commands: init Initialize a serverless application with a... package Package an AWS SAM application. This is an alias for 'aws cloudformation package'. local Run your Serverless application locally for... validate Validate an AWS SAM template. deploy Deploy an AWS SAM application. This is an alias for 'aws cloudformation deploy'.
  • 32. DEMO!
  • 33. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS Cloud9
  • 34. © 2018, 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" ] } } } }
  • 35. { "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
  • 36. { "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 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
  • 37. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS CloudFormation Templates (in action): "ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" }, {"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]},
  • 38. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS CloudFormation Templates (in action): "ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" }, {"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]}, “AWSRegionVirt2AMI” Map
  • 39. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS CloudFormation Templates (in action): "ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" }, {"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]}, “AWSRegionVirt2AMI” Map “AWSInstanceType2Virt” Map
  • 40. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS CloudFormation Templates (in action): "ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" }, {"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]}, “AWSRegionVirt2AMI” Map “AWSInstanceType2Virt” Map “myInstanceType” Parameter
  • 41. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS CloudFormation Templates (in action): "ImageId" : { "Fn::FindInMap" : [ "AWSRegionVirt2AMI", { "Ref" : "AWS::Region" }, {"Fn::FindInMap": ["AWSInstanceType2Virt", { "Ref" : "myInstanceType" }, "Virt"]} ]}, “AWSRegionVirt2AMI” Map “AWSInstanceType2Virt” Map “myInstanceType” Parameter AWS::Region Pseudo Parameter
  • 42. AWS CloudFormation Parameters: "myInstanceType" : { "Type" : "String", "Default" : "t2.large", "AllowedValues" : ["t2.micro", "t2.small", "t2.medium", "t2.large"], "Description" : "Instance type for instances created, must be in the t2 family." } Mappings: "AWSInstanceType2Virt": { "t2.micro": {"Virt": "HVM"}, "t2.small": {"Virt": "HVM"}, "t2.medium": {"Virt": "HVM"}, "t2.large": {"Virt": "HVM"}, } Mappings: "AWSRegionVirt2AMI": { "us-east-1": { "PVM": "ami-50842d38", "HVM": "ami-08842d60" }, "us-west-2": { "PVM": "ami-af86c69f", "HVM": "ami-8786c6b7" }, "us-west-1": { "PVM": "ami-c7a8a182", "HVM": "ami-cfa8a18a" } }
  • 43. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Template Capabilities • Can mix in other non-SAM CloudFormation resources in the same template • i.e. S3, Kinesis, Step Functions • Supports use of Parameters, Mappings, Outputs, etc • Supports Intrinsic Functions • Can use ImportValue (exceptions for RestApiId, Policies, StageName attributes) • YAML or JSON
  • 44. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 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)
  • 45. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 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
  • 46. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda and API Gateway Variables + SAM Parameters: MyEnvironment: Type: String Default: testing AllowedValues: - testing - staging - prod Description: Environment of this stack of resources SpecialFeature1: Type: String Default: false AllowedValues: - true - false Description: Enable new SpecialFeature1 … #Lambda MyFunction: Type: 'AWS::Serverless::Function' Properties: … Environment: Variables: ENVIRONMENT: !Ref: MyEnvironment Spec_Feature1: !Ref: SpecialFeature1 … #API Gateway MyApiGatewayApi: Type: AWS::Serverless::Api Properties: … Variables: ENVIRONMENT: !Ref: MyEnvironment SPEC_Feature1: !Ref: SpecialFeature1 …
  • 47. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM + Safe Deployments MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs4.3 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
  • 48. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM + Safe Deployments MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs4.3 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
  • 49. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 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:
  • 50. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. 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 In SAM: Note: You can specify a maximum of 10 alarms
  • 51. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Globals Globals: Function: Runtime: nodejs4.3 CodeUri: s3://sam-demo-bucket/todo_list.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
  • 52. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Policy Templates MyFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Give just CRUD permissions to one table - DynamoDBCrudPolicy: TableName: !Ref MyTable ... MyTable: Type: AWS::Serverless::SimpleTable
  • 53. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Policy Templates MyFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Give just CRUD permissions to one table - DynamoDBCrudPolicy: TableName: !Ref MyTable ... MyTable: Type: AWS::Serverless::SimpleTable All found here: https://github.com/awslabs/serverless- application- model/blob/develop/docs/policy_templates _data/policy_templates.json
  • 54. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Best Practices
  • 55. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SAM Best Practices • Use Parameters and Mappings when possible to build dynamic templates based on user inputs and pseudo parameters such as AWS::Region • Use the Globals section to simplify templates • Use ExportValue & ImportValue to share resource information across stacks • Build out multiple environments, such as for Development, Test, Production and even DR using the same template, even across accounts SAM Template Source Control Dev Test Prod
  • 56. SAM Best Practices • Unless function handlers share code, split them into their own independent Lambda functions files or binaries • Another option is to use language specific packages to share common code between functions • Unless independent Lambda functions share event sources, split them into their own code repositories with their own SAM templates • Locally lint your YAML or JSON SAM files before committing them. Then do it again in your CI/CD process
  • 57. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. A serverless application delivery pipeline: This pipeline: • Five Stages • Builds code artifact • Three deployed to “Environments” • Uses SAM/CloudFormation to deploy artifact and other AWS resources • Has Lambda custom actions for running my own testing functions • Integrates with a 3rd party tool/service • Has a manual approval before deploying to production • Creates a client SDK at the end Source Source CodeCommit MyApplication Build test-build-source CodeBuild Deploy Testing create-changeset AWS CloudFormation execute-changeset AWS CloudFormation Run-stubs AWS Lambda Deploy Staging create-changeset AWS CloudFormation execute-changeset AWS CloudFormation Run-API-test Runscope QA-Sign-off Manual Approval Review Deploy Prod create-changeset AWS CloudFormation execute-changeset AWS CloudFormation Create SDK AWS Lambda
  • 58. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
  • 59. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. aws.amazon.com/serverless
  • 60. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Chris Munns munns@amazon.com @chrismunnshttps://www.flickr.com/photos/theredproject/3302110152/
  • 61. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. https://secure.flickr.com/photos/dullhunk/202872717/

Notas do Editor

  1. https://secure.flickr.com/photos/mgifford/4525333972
  2. http://smarthome.reviewed.com/features/everything-that-works-with-amazon-echo-alexa
  3. https://www.flickr.com/photos/theredproject/3302110152/
  4. https://secure.flickr.com/photos/dullhunk/202872717/