😸

AWS SAMやってみた

2022/04/26に公開

SAMのHelloWorldをCloud9でやってみました

Cloud9をデフォルトのまま作成します

最初からSAM入ってます!

~/environment $ sam --version
SAM CLI, version 1.33.0

cloud9はpython3.7が入っていました

~/environment $ python --version
Python 3.7.10

サンプルプログラムの生成

~/environment $ 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

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.9
        3 - ruby2.7
        4 - go1.x
        5 - java11
        6 - dotnetcore3.1
        7 - nodejs12.x
        8 - nodejs10.x
        9 - python3.8
        10 - python3.7
        11 - python3.6
        12 - python2.7
        13 - ruby2.5
        14 - java8.al2
        15 - java8
        16 - dotnetcore2.1
Runtime: 10

Project name [sam-app]: 

Cloning 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: sam-app
    Runtime: python3.7
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    
    Next steps can be found in the README file at ./sam-app/README.md
        

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

cloud9に合わせて、python3.7を選択しました

テンプレートが生成されています

~/environment/sam-app $ ls
events  hello_world  __init__.py  README.md  template.yaml  tests
template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

# 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

build

~/environment/sam-app $ sam build
Building codeuri: /home/ec2-user/environment/sam-app/hello_world runtime: python3.7 metadata: {} architecture: x86_64 functions: ['HelloWorldFunction']
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

ローカル実行

bash
~/environment/sam-app $ sam local invoke
Invoking app.lambda_handler (python3.7)
Image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-python3.7
Building image.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Skip pulling image and use local one: public.ecr.aws/sam/emulation-python3.7:rapid-1.33.0-x86_64.

Mounting /home/ec2-user/environment/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
END RequestId: bb0327ee-74fa-414a-9543-e86b0f8375ea
REPORT RequestId: bb0327ee-74fa-414a-9543-e86b0f8375ea  Init Duration: 0.96 ms  Duration: 159.05 ms     Billed Duration: 160 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

unit test

準備
~/environment/sam-app $ pip install pytest pytest-mock --user
実行
~/environment/sam-app $ python -m pytest tests/ -v
==================================================================================================== test session starts =====================================================================================================
platform linux -- Python 3.7.10, pytest-7.1.2, pluggy-1.0.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/ec2-user/environment/sam-app
plugins: mock-3.7.0
collected 1 item                                                                                                                                                                                                             

tests/unit/test_handler.py::test_lambda_handler PASSED                                                                                                                                                                 [100%]

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

初回デプロイ

--guidedのオプションを指定することで、質問に答えていけば、デプロイできます

~/environment/sam-app $ 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]: y
        #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]: y
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: 

        Looking for resources needed for deployment:
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-ifbjgu0pw7v4
         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/287342c7c3751b36647bd1fcb1d80204  452838 / 452838  (100.00%)

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

Initiating deployment
=====================
Uploading to sam-app/fc863a99a75fccb735a45e376e6b6b5b.template  1089 / 1089  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                              LogicalResourceId                                      ResourceType                                           Replacement                                          
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Modify                                               HelloWorldFunction                                     AWS::Lambda::Function                                  False                                                
* Modify                                               ServerlessRestApi                                      AWS::ApiGateway::RestApi                               False                                                
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:617800879522:changeSet/samcli-deploy1650976803/cf19939a-1abd-482e-82b5-3bc188728f8c


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

2022-04-26 12:40:20 - Waiting for stack create/update to complete

CloudFormation events from changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                         ResourceType                                           LogicalResourceId                                      ResourceStatusReason                                 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE_IN_PROGRESS                                     AWS::Lambda::Function                                  HelloWorldFunction                                     -                                                    
UPDATE_COMPLETE                                        AWS::Lambda::Function                                  HelloWorldFunction                                     -                                                    
UPDATE_COMPLETE_CLEANUP_IN_PROGRESS                    AWS::CloudFormation::Stack                             sam-app                                                -                                                    
UPDATE_COMPLETE                                        AWS::CloudFormation::Stack                             sam-app                                                -                                                    
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                                             
Description         Implicit IAM Role created for Hello World function                                                                                                                                                    
Value               arn:aws:iam::617800879522:role/sam-app-HelloWorldFunctionRole-1A0T299GCL8BD                                                                                                                           

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

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

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

CloudFormationにsam-appというスタックが生成され、そこからLambda、IAM Role、 API Gatewayが生成されていました

選択した内容はsamconfig.tomlに保存されていました

samconfig.toml
version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "sam-app"
s3_bucket = "aws-sam-cli-managed-default-samclisourcebucket-ifbjgu0pw7v4"
s3_prefix = "sam-app"
region = "ap-northeast-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
image_repositories = []
APIエンドポイントのリクエスト結果
{"message": "hello world"}

プログラム修正後のデプロイ

hello world → hello sam worldに変更し、再度デプロイします

hello_world/app.py
     return {
         "statusCode": 200,
         "body": json.dumps({
-            "message": "hello world",
+            "message": "hello sam world",
             # "location": ip.text.replace("\n", "")
         }),
     }
~/environment/sam-app $ sam build
Building codeuri: /home/ec2-user/environment/sam-app/hello_world runtime: python3.7 metadata: {} architecture: x86_64 functions: ['HelloWorldFunction']
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
~/environment/sam-app $ sam deploy
Uploading to sam-app/277c925501d5b639da161681da5664a8  452840 / 452840  (100.00%)

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

Initiating deployment
=====================
Uploading to sam-app/67fd7a50129cea9e5bd869c1e6ec02c3.template  1089 / 1089  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                              LogicalResourceId                                      ResourceType                                           Replacement                                          
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Modify                                               HelloWorldFunction                                     AWS::Lambda::Function                                  False                                                
* Modify                                               ServerlessRestApi                                      AWS::ApiGateway::RestApi                               False                                                
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:617800879522:changeSet/samcli-deploy1650977444/15db7445-cfa0-42a7-9995-5b113d017e32


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

2022-04-26 12:51:02 - Waiting for stack create/update to complete

CloudFormation events from changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                         ResourceType                                           LogicalResourceId                                      ResourceStatusReason                                 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE_IN_PROGRESS                                     AWS::Lambda::Function                                  HelloWorldFunction                                     -                                                    
UPDATE_COMPLETE                                        AWS::Lambda::Function                                  HelloWorldFunction                                     -                                                    
UPDATE_COMPLETE_CLEANUP_IN_PROGRESS                    AWS::CloudFormation::Stack                             sam-app                                                -                                                    
UPDATE_COMPLETE                                        AWS::CloudFormation::Stack                             sam-app                                                -                                                    
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs                                                                                                                                                                                                                   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                                                                                                                                             
Description         Implicit IAM Role created for Hello World function                                                                                                                                                    
Value               arn:aws:iam::617800879522:role/sam-app-HelloWorldFunctionRole-1A0T299GCL8BD                                                                                                                           

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

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

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

変更があったLambdaのみデプロイされている

APIエンドポイントのリクエスト結果
{"message": "hello sam world"}

Cleanup

aws cloudformation delete-stack --stack-name sam-app

Discussion