iTranslated by AI
Deploying a Hello World Application with AWS SAM
I want to try using AWS SAM, so I will deploy an application using SAM that calls a Lambda function to display a "Hello World" message via API Gateway.
Prerequisites
- Create an AWS account
- Install Docker
- Install AWS SAM CLI
- It is OK if the version is displayed when you run "sam --version"
Downloading the Sample Application
There is an application that can be downloaded as a sample via the sam command, so we will download it.
First, enter the following command.
$ sam init
During the process, you will select the template source, package type, and runtime.
The project name can be anything you like.
Here, I am using "hello-sam".
$ sam init
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
What package type would you like to use?
1 - Zip (artifact is a zip uploaded to S3)
2 - Image (artifact is an image uploaded to an ECR image repository)
Package type: 1
Which runtime would you like to use?
1 - nodejs14.x
2 - python3.8
3 - ruby2.7
4 - go1.x
5 - java11
6 - dotnetcore3.1
7 - nodejs12.x
8 - nodejs10.x
9 - python3.7
10 - python3.6
11 - python2.7
12 - ruby2.5
13 - java8.al2
14 - java8
15 - dotnetcore2.1
Runtime: 9
Project name [sam-app]: hello-sam
Once you have entered this much, the template will be automatically downloaded locally from GitHub.
Finally, select the template.
Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates
AWS quick start application templates:
1 - Hello World Example
2 - EventBridge Hello World
3 - EventBridge App from scratch (100+ Event Schemas)
4 - Step Functions Sample App (Stock Trader)
Template selection: 1
-----------------------
Generating application:
-----------------------
Name: hello-sam
Runtime: python3.7
Dependency Manager: pip
Application Template: hello-world
Output Directory: .
Next steps can be found in the README file at ./hello-sam/README.md
If you see this, the initial preparation is OK.
Building the Application
Move to the project directory and check the contents.
$ cd hello-sam
$ tree
.
├── README.md
├── __init__.py
├── events
│ └── event.json
├── hello_world
│ ├── __init__.py
│ ├── app.py
│ └── requirements.txt
├── template.yaml
└── tests
├── __init__.py
└── unit
├── __init__.py
└── test_handler.py
The file named template.yaml in this list is important.
In AWS SAM, you create a configuration file called template.yaml and define AWS SAM resources.
The contents of template.yaml look like this:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
hello-sam
Sample SAM Template for hello-sam
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
AWS SAM works by using CloudFormation internally to create AWS resources based on the configuration file you've written as code.
In the Resources section of template.yaml, we define the Lambda and API Gateway we're creating this time.
Now, let's build based on this template.yaml.
$ sam build
...
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
Build Succeeded
Built Artifacts : .aws-sam/build
Built Template : .aws-sam/build/template.yaml
Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided
If "Build Succeeded" is displayed, the build is complete.
Testing Locally
You can deploy as is, but before doing so, you can also run it locally and test the API by calling it locally.
Although you need to have Docker installed, it is convenient and easy because you can execute it in a local environment with a single command.
Normally, API Gateway can only be verified after deploying to the cloud, but to test it locally, you run the sam local start-api command.
$ sam local start-api
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
The start-api command allows you to start an endpoint for local testing (internally, a Docker container is running).
Now, since the URL for local testing is displayed, let's access it using the curl command.
Execute this by opening a separate terminal.
$ curl http://127.0.0.1:3000/hello
{"message": "hello world"}~ $
A Hello World response has been returned in JSON format.
This result is the same as the result you would get if you deployed it to the cloud as an API Gateway.
Deploying to AWS
We were able to test locally without any issues, so let's actually deploy it.
Basically, you just need to run sam deploy --guided and follow the instructions displayed on the screen.
For this setup, we will specify the following:
$ sam deploy --guided
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]:
AWS Region [ap-northeast-1]:
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]: 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]: Y
HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
Save arguments to configuration file [Y/n]: n
CloudFormation runs internally, and once the deployment is complete, it will output the following:
(Some information has been masked)
CloudFormation outputs from deployed stack
--------------------------------------------------------------------------------------------------
Outputs
--------------------------------------------------------------------------------------------------
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::xxxxxxxxxxx:role/sam-app-HelloWorldFunctionRole-XXXXXXXXXX
Key HelloWorldApi
Description API Gateway endpoint URL for Prod stage for Hello World function
Value https://xxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:sam-app-
HelloWorldFunction-DL88K6
--------------------------------------------------------------------------------------------------
Successfully created/updated stack - sam-app in ap-northeast-1
To test the API with the curl command, access the URL displayed in the Value column for the Key HelloWorldApi.
$ curl https://xxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message": "hello world"}
You can see that the same response as when testing locally is returned.
Discussion