Accept
This website is using cookies. More details

Pierre Renard
Cloud technologies addict. Pierre enjoys making awesome cloud-based solutions.

Deploying Serverless applications with AWS SAM

Deploying Serverless applications with AWS SAM

Serverless architectures emerged in 2014 with the release of AWS Lambda. The concept of serverless architecture allows developers to build and run applications without managing servers, automatically scaling resources based on demand. This is achieved through AWS services like AWS Lambda, which executes code in response to events, and AWS API Gateway, which manages API requests.

To manage the deployment, several developer tools were released to help developers deploy their serverless applications easily in the cloud. Back in 2018, we tested the AWS Serverless Application Model (SAM) developed and maintained by AWS. The idea behind this project was to ease the development and deployment of serverless applications to the AWS cloud. The first version lacked features that the Serverless Framework had.

Recently, Serverless.com changed their pricing model

According to Serverless.com, the new version (V4) of the Serverless Framework will be paid.

As we announced at the end of 2023, Serverless Framework CLI will continue to be free for individual developers and small businesses, but will no longer be free for Organizations that have greater than $2M in annual revenue. These Organizations will require a commercial Subscription. These changes only apply to Serverless Framework V.4 and beyond and not to earlier versions. Serverless Framework V.3 will continue to be maintained via critical security and bug fixes through 2024. Serverless.com

With the new pricing model of the Serverless Framework, the situation had changed. It’s time to review new features of the AWS SAM.

AWS Serverless Application Model (SAM)

Overview

AWS SAM is composed of two main components; AWS SAM templates and the AWS SAM Command Line Interface (AWS SAM CLI).

  • The SAM templates offer a simplified syntax designed for defining Infrastructure as Code (IaC) for serverless applications. This allows you to deploy SAM templates directly through CloudFormation.
  • The AWS SAM CLI is a developer tool that provides an easy way to to test and deploy your Serverless application in AWS.

What’s new since 2018?

Since 2018, the AWS Serverless Application Model (AWS SAM) tool has evolved and offers several key features to simplify building and running serverless applications on AWS.

Added sam build to the AWS SAM CLI: The new sam build command in the AWS SAM CLI simplifies the process for compiling serverless applications with dependencies so that you can test locally and then deploy. For more information, see Building applications.

Nested applications and layers support: Added support for nested applications and layers.

  • Orchestrating serverless applications: Added support for orchestrating applications by creating Step Functions state machines using AWS SAM using the resource type AWS::Serverless::StateMachine.

  • Support for warm containers: Added support for warm containers when testing locally using the AWS SAM CLI commands sam local start-api and sam local start-lambda.

  • Debugging AWS SAM applications with AWS Toolkits: AWS Toolkits now supports step-through debugging with more combinations of integrated development environments (IDEs) and runtimes.

  • Added AWS SAM CLI Terraform support for local debugging and testing: Use the AWS SAM CLI within your Terraform projects to perform local debugging and testing of your Lambda functions and layers.

The project has evolved significantly since the beginning, bringing real added value with the support of various features from AWS, such as X-Ray monitoring and the debugging. Let’s create a sample project to explore these new features.

Creating and deploying a Serverless application with AWS SAM

Prerequisites

First, let’s download and install the latest version of the AWS SAM CLI following Installing the AWS SAM CLI.

Once done, you should be able to list all available commands by typing sam -h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Usage: sam [OPTIONS] COMMAND [ARGS]...

  AWS Serverless Application Model (SAM) CLI

  The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) is
  a command line tool that you can use with AWS SAM templates and supported
  third-party integrations to build and run your serverless applications.

  Learn more: https://docs.aws.amazon.com/serverless-application-model/

Commands:

  Learn:
    docs NEW!           Launch the AWS SAM CLI documentation in a browser.

  Create an App:
    init                Initialize an AWS SAM application.

  Develop your App:
    build               Build your AWS serverless function code.
    local               Run your AWS serverless function locally.
    validate            Validate an AWS SAM template.
    sync NEW!           Sync an AWS SAM project to AWS.
    remote NEW!         Invoke or send an event to cloud resources in your AWS
                        Cloudformation stack.

  Deploy your App:
    package             Package an AWS SAM application.
    deploy              Deploy an AWS SAM application.

  Monitor your App:
    logs                Fetch AWS Cloudwatch logs for AWS Lambda Functions or
                        Cloudwatch Log groups.
    traces              Fetch AWS X-Ray traces.

  And More:
    list NEW!           Fetch the state of your AWS serverless application.
    delete              Delete an AWS SAM application and the artifacts created
                        by sam deploy.
    pipeline            Manage the continuous delivery of your AWS serverless
                        application.
    publish             Publish a packaged AWS SAM template to AWS Serverless
                        Application Repository for easy sharing.

Options:
                                    
    --beta-features / --no-beta-features
                                    Enable/Disable beta features.
    --debug                         Turn on debug logging to print debug message
                                    generated by AWS SAM CLI and display
                                    timestamps.
    --version                       Show the version and exit.
    --info                          Show system and dependencies information.
    -h, --help                      Show this message and exit.

Examples:
                        
    Get Started:        $sam init

Creating the application

Let’s create our application. There are several templates available to test and deploy quickly a Serverless application to the cloud. To bootstrap a demo environment, type sam init and select the Hello World Example with PowerTools for AWS Lambda.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
$ sam init

        SAM CLI now collects telemetry to better understand customer needs.

        You can OPT OUT and disable telemetry collection by setting the
        environment variable SAM_CLI_TELEMETRY=0 in your shell.
        Thanks for your help!

        Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html


You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.

Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Data processing
        3 - Hello World Example with Powertools for AWS Lambda
        4 - Multi-step workflow
        5 - Scheduled task
        6 - Standalone function
        7 - Serverless API
        8 - Infrastructure event management
        9 - Lambda Response Streaming
        10 - Serverless Connector Hello World Example
        11 - Multi-step workflow with Connectors
        12 - GraphQLApi Hello World Example
        13 - Full Stack
        14 - Lambda EFS example
        15 - DynamoDB Example
        16 - Machine Learning
Template: 3

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - java17
        4 - java11
        5 - java8.al2
        6 - nodejs20.x
        7 - nodejs18.x
        8 - nodejs16.x
        9 - python3.9
        10 - python3.8
        11 - python3.12
        12 - python3.11
        13 - python3.10
Runtime: 11

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is pip.
We will proceed copying the template using pip.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: y
X-Ray will incur an additional cost. View https://aws.amazon.com/xray/pricing/ for more details

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: y
AppInsights monitoring may incur additional cost. View https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-what-is.html#appinsights-pricing for more details

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: y
Structured Logging in JSON format might incur an additional cost. View https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html#monitoring-cloudwatchlogs-pricing for more details

Project name [sam-app]: 
                                                                                                                                                                   
Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)                                                                          

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Runtime: python3.12
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world-powertools-python
    Output Directory: .
    Configuration file: sam-app/samconfig.toml
    
    Next steps can be found in the README file at sam-app/README.md
        

Commands you can use next
=========================
[*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
[*] Validate SAM template: cd sam-app && sam validate
[*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch


SAM CLI update available (1.118.0); (1.117.0 installed)
To download: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html

What are Powertools for AWS Lambda?

Powertools for AWS Lambda is a developer toolkit to implement Serverless best practices and increase developer velocity. The toolkit helps to implement common patterns including:

  • Tracing: Powertools integrates with AWS X-Ray to provide distributed tracing capabilities. You can trace requests across multiple Lambda functions, API Gateway, and other AWS services. This helps you identify bottlenecks and troubleshoot performance issues.
  • Structured Logging: Powertools encourages structured logging by providing a logger that formats log messages in a consistent way. This makes it easier to analyze logs and extract relevant information with AWS CloudWatch insight for example.
  • Retries and Circuit Breakers: Powertools includes utilities for handling retries and implementing circuit breakers.
  • Error Handling: Powertools simplifies error handling by providing an error handler that logs errors and captures relevant context. It also integrates with AWS Step Functions.

This list is non-exhaustive and there is many more features and helpers.

Building the application

Now that we have created the project, the next step is to package the application. The sam build command is a part of the AWS SAM CLI, which will help us build and package the serverless application using AWS SAM templates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ sam build
Starting Build use cache                                                                                                                                           
Manifest file is changed (new hash: 9b9825447f25c5574b2a1972c68ffd78) or dependency folder (.aws-sam/deps/4a20e72f-8b4c-4cf7-b73c-06929d5e9c0d) is missing for     
(HelloWorldFunction), downloading dependencies and copying/building source                                                                                         
Building codeuri: /sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions:          
HelloWorldFunction                                                                                                                                                 
 Running PythonPipBuilder:CleanUp                                                                                                                                  
 Running PythonPipBuilder:ResolveDependencies                                                                                                                      
 Running PythonPipBuilder:CopySource                                                                                                                               
 Running PythonPipBuilder:CopySource                                                                                                                               

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name  --watch
[*] Deploy: sam deploy --guided

Deploying the application

Once built, we can deploy the application with the sam deploy command. The deployment process leverages CloudFormation to deploy the application as a CloudFormation stack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
$ sam deploy --guided

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

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

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: 
        AWS Region [us-east-1]: eu-west-1
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: 
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: 
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: 
        HelloWorldFunction has no authentication. Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: 
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: dev

        Looking for resources needed for deployment:
        Creating the required resources...
        Successfully created!

        Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-kwzfelz3b9ka
        A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False

        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at 
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

        Uploading to sam-app/30630909cbc282d2f28c67b173a7e0f8  14063310 / 14063310  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : eu-west-1
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-kwzfelz3b9ka
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to sam-app/225d20703d2fd219fd18f4e72787759e.template  1927 / 1927  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                               LogicalResourceId                       ResourceType                            Replacement                           
-------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                   ApplicationInsightsMonitoring           AWS::ApplicationInsights::Application   N/A                                   
+ Add                                   ApplicationResourceGroup                AWS::ResourceGroups::Group              N/A                                   
+ Add                                   HelloWorldFunctionHelloPathPermission   AWS::Lambda::Permission                 N/A                                   
                                        Prod                                                                                                                  
+ Add                                   HelloWorldFunctionRole                  AWS::IAM::Role                          N/A                                   
+ Add                                   HelloWorldFunction                      AWS::Lambda::Function                   N/A                                   
+ Add                                   ServerlessRestApiDeployment47fc2d5f9d   AWS::ApiGateway::Deployment             N/A                                   
+ Add                                   ServerlessRestApiProdStage              AWS::ApiGateway::Stage                  N/A                                   
+ Add                                   ServerlessRestApi                       AWS::ApiGateway::RestApi                N/A                                   
-------------------------------------------------------------------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:eu-west-1:123456789:changeSet/samcli-deploy1718024968/4cf50ca8-5702-45c0-99b6-30437e54c8b3


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2024-06-10 15:09:47 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                          ResourceType                            LogicalResourceId                       ResourceStatusReason                  
-------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                      AWS::CloudFormation::Stack              sam-app                                 User Initiated                        
CREATE_IN_PROGRESS                      AWS::IAM::Role                          HelloWorldFunctionRole                  -                                     
CREATE_IN_PROGRESS                      AWS::ResourceGroups::Group              ApplicationResourceGroup                -                                     
CREATE_IN_PROGRESS                      AWS::ResourceGroups::Group              ApplicationResourceGroup                Resource creation Initiated           
CREATE_IN_PROGRESS                      AWS::IAM::Role                          HelloWorldFunctionRole                  Resource creation Initiated           
CREATE_COMPLETE                         AWS::ResourceGroups::Group              ApplicationResourceGroup                -                                     
CREATE_IN_PROGRESS                      AWS::ApplicationInsights::Application   ApplicationInsightsMonitoring           -                                     
CREATE_IN_PROGRESS                      AWS::ApplicationInsights::Application   ApplicationInsightsMonitoring           Resource creation Initiated           
CREATE_COMPLETE                         AWS::IAM::Role                          HelloWorldFunctionRole                  -                                     
CREATE_IN_PROGRESS                      AWS::Lambda::Function                   HelloWorldFunction                      -                                     
CREATE_IN_PROGRESS                      AWS::Lambda::Function                   HelloWorldFunction                      Resource creation Initiated           
CREATE_IN_PROGRESS                      AWS::Lambda::Function                   HelloWorldFunction                      Eventual consistency check initiated  
CREATE_IN_PROGRESS                      AWS::ApiGateway::RestApi                ServerlessRestApi                       -                                     
CREATE_IN_PROGRESS                      AWS::ApiGateway::RestApi                ServerlessRestApi                       Resource creation Initiated           
CREATE_COMPLETE                         AWS::ApiGateway::RestApi                ServerlessRestApi                       -                                     
CREATE_IN_PROGRESS                      AWS::ApiGateway::Deployment             ServerlessRestApiDeployment47fc2d5f9d   -                                     
CREATE_IN_PROGRESS                      AWS::Lambda::Permission                 HelloWorldFunctionHelloPathPermission   -                                     
                                                                                Prod                                                                          
CREATE_IN_PROGRESS                      AWS::Lambda::Permission                 HelloWorldFunctionHelloPathPermission   Resource creation Initiated           
                                                                                Prod                                                                          
CREATE_IN_PROGRESS                      AWS::ApiGateway::Deployment             ServerlessRestApiDeployment47fc2d5f9d   Resource creation Initiated           
CREATE_COMPLETE                         AWS::Lambda::Permission                 HelloWorldFunctionHelloPathPermission   -                                     
                                                                                Prod                                                                          
CREATE_COMPLETE                         AWS::ApiGateway::Deployment             ServerlessRestApiDeployment47fc2d5f9d   -                                     
CREATE_COMPLETE                         AWS::Lambda::Function                   HelloWorldFunction                      -                                     
CREATE_IN_PROGRESS                      AWS::ApiGateway::Stage                  ServerlessRestApiProdStage              -                                     
CREATE_IN_PROGRESS                      AWS::ApiGateway::Stage                  ServerlessRestApiProdStage              Resource creation Initiated           
CREATE_COMPLETE                         AWS::ApiGateway::Stage                  ServerlessRestApiProdStage              -                                     
CREATE_IN_PROGRESS                      AWS::ApplicationInsights::Application   ApplicationInsightsMonitoring           Eventual consistency check initiated  
CREATE_IN_PROGRESS                      AWS::CloudFormation::Stack              sam-app                                 Eventual consistency check initiated  
CREATE_COMPLETE                         AWS::ApplicationInsights::Application   ApplicationInsightsMonitoring           -                                     
CREATE_COMPLETE                         AWS::CloudFormation::Stack              sam-app                                 -                                     
-------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                        
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldApi                                                                                                                              
Description         API Gateway endpoint URL for Prod environment for Hello World Function                                                                     
Value               https://x4anr51xta.execute-api.eu-west-1.amazonaws.com/Prod/hello                                                                          

Key                 HelloWorldFunction                                                                                                                         
Description         Hello World Lambda Function ARN                                                                                                            
Value               arn:aws:lambda:eu-west-1:123456789:function:sam-app-HelloWorldFunction-AB8K6fc0nA4k                                                     
----------------------------------------------------------------------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-app in eu-west-1 

Collecting traces

Now that, that our application is deployed, you can call the endpoint deployed to interact with the application. In our example, the endpoint is displayed in the “Outputs” section of the deployment phase (https://x4anr51xta.execute-api.eu-west-1.amazonaws.com/Prod/hello). Each call will be tracked thanks to the Amazon X-Ray integration. Amazon X-Ray is a distributed tracing service provided by AWS that helps developers analyze and debug applications, particularly those built using serverless architecture. By running the sam traces command, you can see various figures including statistics to monitor the performance of serverless applications.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
$ sam traces

New XRay Service Graph
  Start time: 2024-06-10 16:18:27+02:00
  End time: 2024-06-10 16:20:52+02:00
  Reference Id: 0 - (Root) AWS::Lambda - sam-app-HelloWorldFunction-AB8K6fc0nA4k - Edges: [1]
   Summary_statistics:
     - total requests: 6
     - ok count(2XX): 4
     - error count(4XX): 2
     - fault count(5XX): 0
     - total response time: 1.451
  Reference Id: 1 - AWS::Lambda::Function - sam-app-HelloWorldFunction-AB8K6fc0nA4k - Edges: []
   Summary_statistics:
     - total requests: 6
     - ok count(2XX): 4
     - error count(4XX): 2
     - fault count(5XX): 0
     - total response time: 0.127
  Reference Id: 2 - client - sam-app-HelloWorldFunction-AB8K6fc0nA4k - Edges: [0]
   Summary_statistics:
     - total requests: 0
     - ok count(2XX): 0
     - error count(4XX): 0
     - fault count(5XX): 0
     - total response time: 0

XRay Event [revision 2] at (2024-06-10T16:18:58.872000) with id (1-66670b52-6960275a1e97c8a319174fec) and duration (0.022s)
 - 0.022s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.013s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 0.003s - Invocation
     - 0.000s - ## lambda_handler
   - 0.010s - Overhead

XRay Event [revision 2] at (2024-06-10T16:20:52.707000) with id (1-66670bc4-79a8ca57482ac6924aced403) and duration (0.046s)
 - 0.046s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.021s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 0.002s - Invocation
     - 0.001s - ## lambda_handler
       - 0.000s - ## app.hello
   - 0.019s - Overhead

XRay Event [revision 1] at (2024-06-10T16:18:27.711000) with id (1-66670b33-44c443587d4071f46f7d2b9b) and duration (1.326s)
 - 1.326s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.056s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 1.057s - Initialization
   - 0.055s - Invocation
     - 0.014s - ## lambda_handler
   - 0.001s - Overhead

XRay Event [revision 2] at (2024-06-10T16:20:25.402000) with id (1-66670ba9-38312f37626045c908c73c00) and duration (0.011s)
 - 0.011s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.004s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 0.003s - Invocation
     - 0.001s - ## lambda_handler
       - 0.000s - ## app.hello
   - 0.001s - Overhead

XRay Event [revision 2] at (2024-06-10T16:19:40.314000) with id (1-66670b7c-73cea4c054ebc05441a190ed) and duration (0.019s)
 - 0.019s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.012s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 0.002s - Invocation
     - 0.001s - ## lambda_handler
       - 0.000s - ## app.hello
   - 0.010s - Overhead

XRay Event [revision 2] at (2024-06-10T16:19:52.067000) with id (1-66670b88-64ecf7c82a87e8a43e2b0f4b) and duration (0.027s)
 - 0.027s - sam-app-HelloWorldFunction-AB8K6fc0nA4k [HTTP: 200]
 - 0.020s - sam-app-HelloWorldFunction-AB8K6fc0nA4k
   - 0.002s - Invocation
     - 0.001s - ## lambda_handler
       - 0.000s - ## app.hello
   - 0.018s - Overhead

Reviewing logs

The sam logs command allows developers to retrieve, filter, and view logs generated by AWS Lambda functions. It simplifies the process of debugging and monitoring serverless applications by providing direct access to the log data from AWS CloudWatch Logs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
$ sam logs
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:18:58.877000 {
  "time": "2024-06-10T14:18:58.877Z",
  "type": "platform.start",
  "record": {
    "requestId": "74c13bd7-70e0-4c6d-be25-118265d76ed5",
    "version": "$LATEST",
    "tracing": {
      "spanId": "24d5df43596cedd4",
      "type": "X-Amzn-Trace-Id",
      "value": "Root=1-66670b52-6960275a1e97c8a319174fec;Parent=68cfe6bfe7a72879;Sampled=1"
    }
  }
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:18:58.879000 LAMBDA_WARNING: Unhandled exception. The most likely cause is an issue in the function code. However, in rare cases, a Lambda runtime update can cause unexpected function behavior. For functions using managed runtimes, runtime updates can be triggered by a function change, or can be applied automatically. To determine if the runtime has been updated, check the runtime version in the INIT_START log entry. If this error correlates with a change in the runtime version, you may be able to mitigate this error by temporarily rolling back to the previous runtime version. For more information, see https://docs.aws.amazon.com/lambda/latest/dg/runtimes-update.html
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:18:58.879000 {
  "timestamp": "2024-06-10T14:18:58Z",
  "log_level": "ERROR",
  "errorMessage": "'path'",
  "errorType": "KeyError",
  "requestId": "74c13bd7-70e0-4c6d-be25-118265d76ed5",
  "stackTrace": [
    "  File \"/var/task/aws_lambda_powertools/logging/logger.py\", line 450, in decorate\n    return lambda_handler(event, context, *args, **kwargs)\n",
    "  File \"/var/task/aws_lambda_powertools/tracing/tracer.py\", line 317, in decorate\n    response = lambda_handler(event, context, **kwargs)\n",
    "  File \"/var/task/aws_lambda_powertools/metrics/provider/base.py\", line 205, in decorate\n    response = lambda_handler(event, context, *args, **kwargs)\n",
    "  File \"/var/task/app.py\", line 34, in lambda_handler\n    return app.resolve(event, context)\n",
    "  File \"/var/task/aws_lambda_powertools/event_handler/api_gateway.py\", line 1979, in resolve\n    response = self._resolve().build(self.current_event, self._cors)\n",
    "  File \"/var/task/aws_lambda_powertools/event_handler/api_gateway.py\", line 2074, in _resolve\n    path = self._remove_prefix(self.current_event.path)\n",
    "  File \"/var/task/aws_lambda_powertools/utilities/data_classes/common.py\", line 168, in path\n    return self[\"path\"]\n",
    "  File \"/var/task/aws_lambda_powertools/utilities/data_classes/common.py\", line 32, in __getitem__\n    return self._data[key]\n"
  ]
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:18:58.892000 {
  "time": "2024-06-10T14:18:58.892Z",
  "type": "platform.report",
  "record": {
    "requestId": "74c13bd7-70e0-4c6d-be25-118265d76ed5",
    "metrics": {
      "durationMs": 13.539,
      "billedDurationMs": 14,
      "memorySizeMB": 128,
      "maxMemoryUsedMB": 76
    },
    "tracing": {
      "spanId": "24d5df43596cedd4",
      "type": "X-Amzn-Trace-Id",
      "value": "Root=1-66670b52-6960275a1e97c8a319174fec;Parent=68cfe6bfe7a72879;Sampled=1"
    },
    "status": "success"
  }
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:40.318000 {
  "time": "2024-06-10T14:19:40.318Z",
  "type": "platform.start",
  "record": {
    "requestId": "8b9bab4a-05f2-4536-9b53-305dd5e07490",
    "version": "$LATEST",
    "tracing": {
      "spanId": "123e551270dc66ec",
      "type": "X-Amzn-Trace-Id",
      "value": "Root=1-66670b7c-73cea4c054ebc05441a190ed;Parent=02d96360c8900d1d;Sampled=1"
    }
  }
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:40.319000 {
  "level": "INFO",
  "location": "hello:23",
  "message": "Hello world API - HTTP 200",
  "timestamp": "2024-06-10 14:19:40,319+0000",
  "service": "PowertoolsHelloWorld",
  "cold_start": false,
  "function_name": "sam-app-HelloWorldFunction-AB8K6fc0nA4k",
  "function_memory_size": "128",
  "function_arn": "arn:aws:lambda:eu-west-1:123456789:function:sam-app-HelloWorldFunction-AB8K6fc0nA4k",
  "function_request_id": "8b9bab4a-05f2-4536-9b53-305dd5e07490",
  "xray_trace_id": "1-66670b7c-73cea4c054ebc05441a190ed"
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:40.320000 {
  "_aws": {
    "Timestamp": 1718029180320,
    "CloudWatchMetrics": [
      {
        "Namespace": "Powertools",
        "Dimensions": [
          [
            "function_name",
            "service"
          ]
        ],
        "Metrics": [
          {
            "Name": "ColdStart",
            "Unit": "Count"
          }
        ]
      }
    ]
  },
  "function_name": "sam-app-HelloWorldFunction-AB8K6fc0nA4k",
  "service": "PowertoolsHelloWorld",
  "ColdStart": [
    1.0
  ]
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:40.320000 {
  "_aws": {
    "Timestamp": 1718029180320,
    "CloudWatchMetrics": [
      {
        "Namespace": "Powertools",
        "Dimensions": [
          [
            "service"
          ]
        ],
        "Metrics": [
          {
            "Name": "HelloWorldInvocations",
            "Unit": "Count"
          }
        ]
      }
    ]
  },
  "service": "PowertoolsHelloWorld",
  "HelloWorldInvocations": [
    1.0
  ]
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:40.332000 {
  "time": "2024-06-10T14:19:40.332Z",
  "type": "platform.report",
  "record": {
    "requestId": "8b9bab4a-05f2-4536-9b53-305dd5e07490",
    "metrics": {
      "durationMs": 12.623,
      "billedDurationMs": 13,
      "memorySizeMB": 128,
      "maxMemoryUsedMB": 76
    },
    "tracing": {
      "spanId": "123e551270dc66ec",
      "type": "X-Amzn-Trace-Id",
      "value": "Root=1-66670b7c-73cea4c054ebc05441a190ed;Parent=02d96360c8900d1d;Sampled=1"
    },
    "status": "success"
  }
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:52.073000 {
  "_aws": {
    "Timestamp": 1718029192073,
    "CloudWatchMetrics": [
      {
        "Namespace": "Powertools",
        "Dimensions": [
          [
            "service"
          ]
        ],
        "Metrics": [
          {
            "Name": "HelloWorldInvocations",
            "Unit": "Count"
          }
        ]
      }
    ]
  },
  "service": "PowertoolsHelloWorld",
  "HelloWorldInvocations": [
    1.0
  ]
}
2024/06/10/[$LATEST]51c05f8482a748bea023972090a0ee9d 2024-06-10T14:19:52.073000 {
  "level": "INFO",
  "location": "hello:23",
  "message": "Hello world API - HTTP 200",
  "timestamp": "2024-06-10 14:19:52,072+0000",
  "service": "PowertoolsHelloWorld",
  "cold_start": false,
  "function_name": "sam-app-HelloWorldFunction-AB8K6fc0nA4k",
  "function_memory_size": "128",
  "function_arn": "arn:aws:lambda:eu-west-1:123456789:function:sam-app-HelloWorldFunction-AB8K6fc0nA4k",
  "function_request_id": "c7ea361b-7660-4e4d-bb5c-5646fb990ffd",
  "xray_trace_id": "1-66670b88-64ecf7c82a87e8a43e2b0f4b"
}

Testing the application

During the development, you can either deploy in a local container or deploy to a development AWS account and test it. To deploy the application in AWS, run the sam deploy command and wait CloudFormation to deploy your new code.

During the development phase, the sam sync command is a valuable addition. It listens for changes and deploys your updates upon saving, eliminating the need to run the sam deploy command every time you want to deploy. The sync command takes care of that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$ sam sync
                                                                                                                                                                                                        
The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without                                                                                         
performing a CloudFormation deployment. This will cause drift in your CloudFormation stack.                                                                                                             
**The sync command should only be used against a development stack**.                                                                                                                                   
                                                                                                                                                                                                        
Queued infra sync. Waiting for in progress code syncs to complete...                                                                                                                                    
Starting infra sync.                                                                                                                                                                                    
Manifest is not changed for (HelloWorldFunction), running incremental build                                                                                                                             
Building codeuri: /sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions: HelloWorldFunction                            
 Running PythonPipBuilder:CopySource                                                                                                                                                                    

Build Succeeded

Successfully packaged artifacts and wrote output template to file /var/folders/cp/7r2048gj5kz2b2dc5zq_tqpjkrz080/T/tmpacplreoo.
Execute the following command to deploy the packaged template
sam deploy --template-file /var/folders/cp/7r2048gj5kz2b2dc5zq_tqpjkrz080/T/tmpacplreoo --stack-name <YOUR STACK NAME>

Template haven't been changed since last deployment, skipping infra sync...                                                                                                                             
CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.                                                                                                                   
Skipped infra sync as the local template is in sync with the cloud template.                                                                                                                            
Syncing Lambda Function HelloWorldFunction...                                                                                                                                                           
Manifest is not changed for (HelloWorldFunction), running incremental build                                                                                                                             
Building codeuri: /sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions: HelloWorldFunction                            
 Running PythonPipBuilder:CopySource                                                                                                                                                                    
11/Jun/2024:09:27:20: Finished syncing Lambda Function HelloWorldFunction.                                                                                                                              
Syncing Lambda Function HelloWorldFunction...                                                                                                                                                           
Manifest is not changed for (HelloWorldFunction), running incremental build                                                                                                                             
Building codeuri: /sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions: HelloWorldFunction                            
 Running PythonPipBuilder:CopySource                                                                                                                                                                    
11/Jun/2024:09:27:35: Finished syncing Lambda Function HelloWorldFunction.                                                     

Deleting your application

Finally, you can clean the application with the sam delete command which takes care of deleting all assets deployed in the AWS account.

1
2
3
4
5
6
7
8
9
$ sam delete
        Are you sure you want to delete the stack sam-app in the region eu-west-1 ? [y/N]: y
        Do you want to delete the template file cc403f611eb48b6c39b35d24f709fde3.template in S3? [y/N]: y
        - Deleting S3 object with key a3c75f5e286394a6e5e2ff7a8cbe52aa                                                                                                                   
        - Deleting S3 object with key 7c21bb1de8206abcd225e315459dc167.template                                                                                                          
        - Deleting S3 object with key cc403f611eb48b6c39b35d24f709fde3.template                                                                                                          
        - Deleting Cloudformation stack sam-app

Deleted successfully

Conclusion

In this blog post, we have seen that AWS SAM is evolving in a good way with new features that make the development of Serverless applications easier. The framework is developed and maintained by AWS and the community. The documentation is also well-written. AWS SAM is definitely a good alternative to the Serverless.com framework!

Never stop learning

There are a lot of good blogs following the latest news on Serverless. Among them, serverlessland.com is a gold mine. There are guides and workshops worth reading. Also, keep an eye on Powertools for AWS Lambda and be sure to read the latest updates on Serverless news for AWS.

Now it’s your turn!

Schedule a 1-on-1 with an ARHS Cloud Expert today!