🚴🏻‍♀️

SAMでのHello World

2023/01/16に公開約20,000字

やりたいこと

SAMでの勉強整理としてのメモ
やることは以下。

  • 環境整備@Cloud9
  • sam init,sam build,sam deploy
  • sam local
  • pytest

環境整備

■pyenv

git

git clone https://github.com/yyuu/pyenv.git ~/.pyenv  

bash_profileの編集

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile

bash_profileの適用

source ~/.bash_profile

python 3.9.0をInstall

Lambdaで利用可能なPythonに合わせたモノ

pyenv install 3.9.0

Version確認

3.9.0であることを確認

pyenv global 3.9.0
python --version

■AWS CLIをV1からV2へ

version確認

V1系であること

aws --version

uninstall

sudo yum remove awscli

installとbash読み込み

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
source ~/.bash_profile

version確認

V2系であること

aws --version

ゴミ削除

rm -rf aws awscliv2.zip

■SAMの最新化

SAMはCloud9にあるけど、最新化。手順は以下参照
https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/serverless-sam-cli-install-linux.html

手順を少し変えながら最新化

Releseの最新が反映されていること

wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip
unzip aws-sam-cli-linux-x86_64.zip -d sam-installation
sudo ./sam-installation/install --update
sam --version

ゴミ削除

rm -rf aws-sam-cli-linux-x86_64.zip sam-installation

SAMでHelloWorld

■init-build-deploy

init

sam init

設定した内容は以下

sam init
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 - Multi-step workflow
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Infrastructure event management
        8 - Serverless Connector Hello World Example
        9 - Multi-step workflow with Connectors
        10 - Lambda EFS example
        11 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: N

Which runtime would you like to use?
        1 - aot.dotnet7 (provided.al2)
        2 - dotnet6
        3 - dotnet5.0
        4 - dotnetcore3.1
        5 - go1.x
        6 - go (provided.al2)
        7 - graalvm.java11 (provided.al2)
        8 - graalvm.java17 (provided.al2)
        9 - java11
        10 - java8.al2
        11 - java8
        12 - nodejs18.x
        13 - nodejs16.x
        14 - nodejs14.x
        15 - nodejs12.x
        16 - python3.9
        17 - python3.8
        18 - python3.7
        19 - ruby2.7
        20 - rust (provided.al2)
Runtime: 16

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 1

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]: N

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]: N

Project name [sam-app]: sam-app-1

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

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

build

cd sam-app-1
sam build

deploy

sam deploy --guided

設定した内容は以下

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

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]: sam-app-1
        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]: 
        #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 may not have authorization defined, Is this okay? [y/N]: Y
        Save arguments to configuration file [Y/n]: 
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: 

        Looking for resources needed for deployment:
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1hsg213hvqm87
         A different default S3 bucket can be set in samconfig.toml

        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-1/5497b8fae9a252df24ea97cfa575db8a  619129 / 619129  (100.00%)

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

Initiating deployment
=====================
Uploading to sam-app-1/f0431308e328641961235682384a4430.template  1206 / 1206  (100.00%)

Waiting for changeset to be created..
CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                       LogicalResourceId                               ResourceType                                    Replacement                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                           HelloWorldFunctionHelloWorldPermissionProd      AWS::Lambda::Permission                         N/A                                           
+ 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:ap-northeast-1:123456789012:changeSet/samcli-deploy1673792015/6f514082-9e3d-44cd-9374-e7f91a6c4730


2023-01-15 14:13:47 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                  ResourceType                                    LogicalResourceId                               ResourceStatusReason                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                              AWS::IAM::Role                                  HelloWorldFunctionRole                          -                                             
CREATE_IN_PROGRESS                              AWS::IAM::Role                                  HelloWorldFunctionRole                          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_COMPLETE                                 AWS::Lambda::Function                           HelloWorldFunction                              -                                             
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                         HelloWorldFunctionHelloWorldPermissionProd      -                                             
CREATE_IN_PROGRESS                              AWS::Lambda::Permission                         HelloWorldFunctionHelloWorldPermissionProd      Resource creation Initiated                   
CREATE_IN_PROGRESS                              AWS::ApiGateway::Deployment                     ServerlessRestApiDeployment47fc2d5f9d           Resource creation Initiated                   
CREATE_COMPLETE                                 AWS::ApiGateway::Deployment                     ServerlessRestApiDeployment47fc2d5f9d           -                                             
CREATE_IN_PROGRESS                              AWS::ApiGateway::Stage                          ServerlessRestApiProdStage                      -                                             
CREATE_IN_PROGRESS                              AWS::ApiGateway::Stage                          ServerlessRestApiProdStage                      Resource creation Initiated                   
CREATE_COMPLETE                                 AWS::ApiGateway::Stage                          ServerlessRestApiProdStage                      -                                             
CREATE_COMPLETE                                 AWS::Lambda::Permission                         HelloWorldFunctionHelloWorldPermissionProd      -                                             
CREATE_COMPLETE                                 AWS::CloudFormation::Stack                      sam-app-1                                       -                                             
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                      
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                
Description         Implicit IAM Role created for Hello World function                                                                                                                       
Value               arn:aws:iam::123456789012:role/sam-app-1-HelloWorldFunctionRole-17TEJXE38WVEX                                                                                            

Key                 HelloWorldApi                                                                                                                                                            
Description         API Gateway endpoint URL for Prod stage for Hello World function                                                                                                         
Value               https://xxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/                                                                                                  

Key                 HelloWorldFunction                                                                                                                                                       
Description         Hello World Lambda Function ARN                                                                                                                                          
Value               arn:aws:lambda:ap-northeast-1:123456789012:function:sam-app-1-HelloWorldFunction-uWkvXSPEyq3Z                                                                            
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - sam-app-1 in ap-northeast-1

API Call

実行

curl https://xxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/

結果

{"message": "hello world"}

■local invoke

ローカル環境でのLambda実行

sam local invoke HelloWorldFunction

結果

Invoking app.lambda_handler (python3.9)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.9:rapid-1.70.0-x86_64.

Mounting /home/ec2-user/environment/sam-app-1/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: ef693a60-ba5d-47ca-a8e6-d07b741c102f Version: $LATEST
END RequestId: ef693a60-ba5d-47ca-a8e6-d07b741c102f
REPORT RequestId: ef693a60-ba5d-47ca-a8e6-d07b741c102f  Init Duration: 0.13 ms  Duration: 474.97 ms     Billed Duration: 475 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

■local start-api

ローカルでAPI GATEWAY経由で実行

sam local start-api

別ターミナルで実行

curl http://127.0.0.1:3000/hello

結果

Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template
2023-01-16 03:08:15  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
Invoking app.lambda_handler (python3.9)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.9:rapid-1.70.0-x86_64.

Mounting /home/ec2-user/environment/sam-app-1/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
END RequestId: dda01c01-9691-472d-b79c-35773573e7c8
REPORT RequestId: dda01c01-9691-472d-b79c-35773573e7c8  Init Duration: 0.05 ms  Duration: 87.90 ms      Billed Duration: 88 ms  Memory Size: 128 MB     Max Memory Used: 128 MB
No Content-Type given. Defaulting to 'application/json'.
2023-01-16 03:09:04 127.0.0.1 - - [16/Jan/2023 03:09:04] "GET /hello HTTP/1.1" 200 -

別ターミナルの結果

{"message": "hello world"}

■local start-lambda

エンドポイント経由で実行

sam local start-lambda

別ターミナルで実行

cd ~/environment/sam-app-1
aws lambda invoke --function-name "HelloWorldFunction" --endpoint-url "http://127.0.0.1:3001" --payload file://events/event.json --cli-binary-format raw-in-base64-out response.json
cat response.json

結果

am local start-lambda
Starting the Local Lambda Service. You can now invoke your Lambda Functions defined in your template through the endpoint.
2023-01-16 03:12:22  * Running on http://127.0.0.1:3001/ (Press CTRL+C to quit)
Invoking app.lambda_handler (python3.9)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.9:rapid-1.70.0-x86_64.

Mounting /home/ec2-user/environment/sam-app-1/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: 08533001-42ed-4ca8-b5fa-76ff73eb2883 Version: $LATEST
END RequestId: 08533001-42ed-4ca8-b5fa-76ff73eb2883
REPORT RequestId: 08533001-42ed-4ca8-b5fa-76ff73eb2883  Init Duration: 2.62 ms  Duration: 66.94 ms      Billed Duration: 67 ms  Memory Size: 128 MB     Max Memory Used: 128 MB
2023-01-16 03:53:08 127.0.0.1 - - [16/Jan/2023 03:53:08] "POST /2015-03-31/functions/HelloWorldFunction/invocations HTTP/1.1" 200 -

別ターミナル結果

{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

ローカルテスト

Install

pip install pytest

Version確認

Version確認というよりInstall確認かな。入って居れば良い。

pytest --version

実行と結果

実行

cd ~/environment/sam-app-1/
pytest ./tests/unit/test_handler.py 

結果

================================================================================ test session starts ================================================================================
platform linux -- Python 3.9.0, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/ec2-user/environment/sam-app-1
collected 1 item                                                                                                                                                                    

tests/unit/test_handler.py .                                                                                                                                                  [100%]

================================================================================= 1 passed in 0.04s =================================================================================

Discussion

ログインするとコメントできます