SlideShare uma empresa Scribd logo
1 de 59
Baixar para ler offline
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Chris Munns
Senior Developer Advocate – AWS Serverless
Authoring and Deploying Serverless
Applications with AWS SAM
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 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:
• 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.© 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.© 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.© 2018, 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
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
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!";
}
Anatomy of a Lambda function
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Using AWS Lambda
Bring your own code
•Node.js, Java, Python, C#, Go
•Bring your own libraries
(even native ones)
Simple resource model
•Select power rating from
128 MB to 3 GB
•CPU and network allocated
proportionately
Flexible use
•Synchronous or
asynchronous
•Integrated with other AWS
services
Flexible authorization
•Securely grant access to
resources and VPCs
•Fine-grained control for
invoking your functions
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
Lambda execution model
Synchronous
(push)
Asynchronous
(event)
Poll-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.
Lambda execution models
Poll-Based
Amazon
SQS
messages
AWS Lambda
service
function
NEW! NEW!
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Using AWS Lambda
Authoring functions
•Cloud9
•WYSIWYG editor or upload
packaged .zip
•Third-party plugins
(Eclipse, Visual Studio)
Monitoring and logging
•Metrics for requests,
errors, and throttles
•Built-in logs to Amazon
CloudWatch Logs
•AWS X-Ray integration
Programming model
•Use processes, threads,
/tmp, sockets normally
•AWS SDK built in (Python
and Node.js)
Stateless
•Persist data using external
storage
•No affinity or access to
underlying infrastructure
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Event sources that trigger AWS Lambda
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
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.© 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)
AWS CloudFormation extension optimized for
serverless
New serverless resource types: functions, APIs, and
tables
Supports anything AWS CloudFormation supports
Open specification (Apache 2.0)
- SAM Translator recently open sourced!
https://github.com/awslabs/serverless-application-model
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
CloudFormation template
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: nodejs6.10
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: nodejs6.10
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
EndpointConfiguration: REGIONAL
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
Tags:
Department: Engineering
AppType: Serverless
SSESpecification:
SSEEnabled: true
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: 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
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'.
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!
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" ] }
}
}
}
© 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" ] }
}
}
}
HEADERS
PARAMETERS
MAPPINGS
RESOURCES
OUTPUTS
CONDITIONALS
© 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" ] }
}
}
}
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
© 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
(AWS 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
Lambda and API Gateway Variables + 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
Lambda and API Gateway Variables + 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
© 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
SAM Globals
Globals:
Function:
Runtime: nodejs4.3
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
© 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
© 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_templa
tes_data/policy_templates.json
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
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
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 & validate 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.
© 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/
Submit Session Feedback
1. Tap the Schedule icon.
2. Select the session you
attended.
3. Tap Session Evaluation to
submit your feedback.
© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Thank you!

Mais conteúdo relacionado

Mais procurados

Improving Infrastructure Governance on AWS - AWS June 2016 Webinar Series
Improving Infrastructure Governance on AWS - AWS June 2016 Webinar SeriesImproving Infrastructure Governance on AWS - AWS June 2016 Webinar Series
Improving Infrastructure Governance on AWS - AWS June 2016 Webinar SeriesAmazon Web Services
 
AWS Systems manager 2019
AWS Systems manager 2019AWS Systems manager 2019
AWS Systems manager 2019John Varghese
 
AWS Serverless Introduction (Lambda)
AWS Serverless Introduction (Lambda)AWS Serverless Introduction (Lambda)
AWS Serverless Introduction (Lambda)Ashish Kushwaha
 
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트) IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트) Amazon Web Services Korea
 
DEV204_Debugging Modern Applications Introduction to AWS X-Ray
DEV204_Debugging Modern Applications Introduction to AWS X-RayDEV204_Debugging Modern Applications Introduction to AWS X-Ray
DEV204_Debugging Modern Applications Introduction to AWS X-RayAmazon Web Services
 
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatchAmazon Web Services
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon Web Services
 
A Brief Look at Serverless Architecture
A Brief Look at Serverless ArchitectureA Brief Look at Serverless Architecture
A Brief Look at Serverless ArchitectureAmazon Web Services
 
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...Amazon Web Services
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaEdureka!
 
A Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS LambdaA Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS LambdaAmazon Web Services
 
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...Amazon Web Services Korea
 
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 ComputingAmazon Web Services
 

Mais procurados (20)

Introduction to Serverless
Introduction to ServerlessIntroduction to Serverless
Introduction to Serverless
 
Improving Infrastructure Governance on AWS - AWS June 2016 Webinar Series
Improving Infrastructure Governance on AWS - AWS June 2016 Webinar SeriesImproving Infrastructure Governance on AWS - AWS June 2016 Webinar Series
Improving Infrastructure Governance on AWS - AWS June 2016 Webinar Series
 
AWS 101
AWS 101AWS 101
AWS 101
 
AWS Containers Day.pdf
AWS Containers Day.pdfAWS Containers Day.pdf
AWS Containers Day.pdf
 
AWS Systems manager 2019
AWS Systems manager 2019AWS Systems manager 2019
AWS Systems manager 2019
 
AWS Serverless Introduction (Lambda)
AWS Serverless Introduction (Lambda)AWS Serverless Introduction (Lambda)
AWS Serverless Introduction (Lambda)
 
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트) IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
IDC 서버 몽땅 AWS로 이전하기 위한 5가지 방법 - 윤석찬 (AWS 테크에반젤리스트)
 
AWS CloudWatch
AWS CloudWatchAWS CloudWatch
AWS CloudWatch
 
DEV204_Debugging Modern Applications Introduction to AWS X-Ray
DEV204_Debugging Modern Applications Introduction to AWS X-RayDEV204_Debugging Modern Applications Introduction to AWS X-Ray
DEV204_Debugging Modern Applications Introduction to AWS X-Ray
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch
(DVO315) Log, Monitor and Analyze your IT with Amazon CloudWatch
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
A Brief Look at Serverless Architecture
A Brief Look at Serverless ArchitectureA Brief Look at Serverless Architecture
A Brief Look at Serverless Architecture
 
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
 
AWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | EdurekaAWS Cloud Practitioner Tutorial | Edureka
AWS Cloud Practitioner Tutorial | Edureka
 
A Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS LambdaA Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS Lambda
 
AWS Technical Essentials Day
AWS Technical Essentials DayAWS Technical Essentials Day
AWS Technical Essentials Day
 
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
 
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
 

Semelhante a Build and Deploy Serverless Applications with AWS SAM

Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep DiveAmazon Web Services
 
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 ...Amazon Web Services
 
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 ComputingAmazon Web Services
 
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 SummitAmazon Web Services
 
Serverless Applications with AWS SAM
Serverless Applications with AWS SAMServerless Applications with AWS SAM
Serverless Applications with AWS SAMChris Munns
 
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 serversAmazon Web Services
 
Serverless use cases with AWS Lambda - More Serverless Event
Serverless use cases with AWS Lambda - More Serverless EventServerless use cases with AWS Lambda - More Serverless Event
Serverless use cases with AWS Lambda - More Serverless EventBoaz Ziniman
 
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 SummitAmazon Web Services
 
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 SAMAmazon Web Services
 
Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...Amazon Web Services
 
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...Amazon Web Services
 
Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep DiveAmazon Web Services
 
Building CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless ApplicationsBuilding CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless ApplicationsAmazon Web Services
 
Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps Amazon Web Services
 
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Chris Munns
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon Web Services
 
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 SummitAmazon Web Services
 
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWSServerless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWSCodeOps Technologies LLP
 
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...Amazon Web Services
 
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...Amazon Web Services
 

Semelhante a Build and Deploy Serverless Applications with AWS SAM (20)

Serverless Development Deep Dive
Serverless Development Deep DiveServerless Development Deep Dive
Serverless Development Deep Dive
 
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 ...
 
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
 
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
 
Serverless Applications with AWS SAM
Serverless Applications with AWS SAMServerless Applications with AWS SAM
Serverless Applications with AWS SAM
 
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
 
Serverless use cases with AWS Lambda - More Serverless Event
Serverless use cases with AWS Lambda - More Serverless EventServerless use cases with AWS Lambda - More Serverless Event
Serverless use cases with AWS Lambda - More Serverless Event
 
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
 
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
 
Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...
 
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...
 
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
 
Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps Build Enterprise-Grade Serverless Apps
Build Enterprise-Grade Serverless Apps
 
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
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
 
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWSServerless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
Serverless Architectural Patterns 
and Best Practices - Madhu Shekar - AWS
 
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...
 
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
 

Mais de Amazon Web Services

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Amazon Web Services
 
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Amazon Web Services
 
Esegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateAmazon Web Services
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSAmazon Web Services
 
Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Amazon Web Services
 
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Amazon Web Services
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...Amazon Web Services
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsAmazon Web Services
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareAmazon Web Services
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSAmazon Web Services
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAmazon Web Services
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareAmazon Web Services
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWSAmazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckAmazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without serversAmazon Web Services
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...Amazon Web Services
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceAmazon Web Services
 

Mais de Amazon Web Services (20)

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
 
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
 
Esegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS Fargate
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWS
 
Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot
 
Open banking as a service
Open banking as a serviceOpen banking as a service
Open banking as a service
 
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 

Build and Deploy Serverless Applications with AWS SAM

  • 1. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Chris Munns Senior Developer Advocate – AWS Serverless Authoring and Deploying Serverless Applications with AWS SAM
  • 2. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 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: • 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.© 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.© 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.© 2018, 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
  • 6. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. 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!"; } Anatomy of a Lambda function
  • 7. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Using AWS Lambda Bring your own code •Node.js, Java, Python, C#, Go •Bring your own libraries (even native ones) Simple resource model •Select power rating from 128 MB to 3 GB •CPU and network allocated proportionately Flexible use •Synchronous or asynchronous •Integrated with other AWS services Flexible authorization •Securely grant access to resources and VPCs •Fine-grained control for invoking your functions
  • 8. 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
  • 9. Lambda execution model Synchronous (push) Asynchronous (event) Poll-Based Amazon API Gateway AWS Lambda function Amazon DynamoDBAmazon SNS /order AWS Lambda function Amazon S3 reqs Amazon Kinesis changes AWS Lambda service function
  • 10. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Lambda execution models Poll-Based Amazon SQS messages AWS Lambda service function NEW! NEW!
  • 11. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Using AWS Lambda Authoring functions •Cloud9 •WYSIWYG editor or upload packaged .zip •Third-party plugins (Eclipse, Visual Studio) Monitoring and logging •Metrics for requests, errors, and throttles •Built-in logs to Amazon CloudWatch Logs •AWS X-Ray integration Programming model •Use processes, threads, /tmp, sockets normally •AWS SDK built in (Python and Node.js) Stateless •Persist data using external storage •No affinity or access to underlying infrastructure
  • 12. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Event sources that trigger AWS Lambda 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 and more! AWS CodeCommit Amazon API Gateway Amazon Alexa AWS IoT AWS Step Functions
  • 13. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 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
  • 15. AWS Serverless Application Model (SAM) AWS CloudFormation extension optimized for serverless New serverless resource types: functions, APIs, and tables Supports anything AWS CloudFormation supports Open specification (Apache 2.0) - SAM Translator recently open sourced! https://github.com/awslabs/serverless-application-model
  • 16. 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
  • 19. 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
  • 20. 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: nodejs6.10 Policies: AmazonDynamoDBReadOnlyAccess Events: GetHtml: Type: Api Properties: Path: /{proxy+} Method: ANY ListTable: Type: AWS::Serverless::SimpleTable
  • 22. 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
  • 23. SAM Template Properties AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable StageName: prod DefinitionUri: swagger.yml CacheClusterEnabled: true CacheClusterSize: 28.4 EndpointConfiguration: REGIONAL Variables: VarName: VarValue From SAM Version 2016-10-31
  • 24. SAM Template Properties AWS::Serverless::Function AWS::Serverless::Api AWS::Serverless::SimpleTable PrimaryKey: Name: id Type: String ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 Tags: Department: Engineering AppType: Serverless SSESpecification: SSEEnabled: true From SAM Version 2016-10-31
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 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
  • 32. 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'.
  • 33. 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'.
  • 34. DEMO!
  • 36. © 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" ] } } } }
  • 37. © 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" ] } } } } HEADERS PARAMETERS MAPPINGS RESOURCES OUTPUTS CONDITIONALS
  • 38. © 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" ] } } } } 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
  • 39. © 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
  • 40. © 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 (AWS 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)
  • 41. © 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
  • 42. Lambda and API Gateway Variables + 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
  • 43. Lambda and API Gateway Variables + 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
  • 44. © 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
  • 45. © 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
  • 46. © 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:
  • 47. © 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
  • 48. SAM Globals Globals: Function: Runtime: nodejs4.3 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
  • 49. © 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
  • 50. © 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
  • 51. © 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_templa tes_data/policy_templates.json
  • 53. © 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
  • 54. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. 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 & validate your YAML or JSON SAM files before committing them. Then do it again in your CI/CD process
  • 55. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 56. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. aws.amazon.com/serverless
  • 57. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Chris Munns munns@amazon.com @chrismunnshttps://www.flickr.com/photos/theredproject/3302110152/
  • 58. Submit Session Feedback 1. Tap the Schedule icon. 2. Select the session you attended. 3. Tap Session Evaluation to submit your feedback.
  • 59. © 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved.© 2018, Amazon Web Services, Inc. or its affiliates. All rights reserved. Thank you!