◆ AWS SAMを使ってLambdaにデプロイする

インフラ

sam init


\sam_test>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: 2

Which base image would you like to use?
        1 - amazon/nodejs14.x-base
        2 - amazon/nodejs12.x-base
        3 - amazon/nodejs10.x-base
        4 - amazon/python3.8-base
        5 - amazon/python3.7-base
        6 - amazon/python3.6-base
        7 - amazon/python2.7-base
        8 - amazon/ruby2.7-base
        9 - amazon/ruby2.5-base
        10 - amazon/go1.x-base
        11 - amazon/java11-base
        12 - amazon/java8.al2-base
        13 - amazon/java8-base
        14 - amazon/dotnet5.0-base
        15 - amazon/dotnetcore3.1-base
        16 - amazon/dotnetcore2.1-base
Base image: 5

Project name [sam-app]: sam-tweepy

Cloning from https://github.com/aws/aws-sam-cli-app-templates

    -----------------------
    Generating application:
    -----------------------
    Name: sam-tweepy
    Base Image: amazon/python3.7-base
    Dependency Manager: pip
    Output Directory: .

    Next steps can be found in the README file at ./sam-tweepy/README.md

sam build

./sam-app $ sam build

実行結果


sam-tweepy>sam build
Building codeuri: C:\Users\youre\Documents\sam_test\sam-tweepy runtime: None metadata: {'DockerTag': 'python3.7-v1', 'DockerContext': 'C:\\Users\\youre\\Documents\\sam_test\\sam-tweepy\\hello_world', 'Dockerfile': 'Dockerfile'} functions: ['HelloWorldFunction']
Building image for HelloWorldFunction function
Setting DockerBuildArgs: {} for HelloWorldFunction function
Step 1/4 : FROM public.ecr.aws/lambda/python:3.7
 ---> 6cce156cc864
Step 2/4 : COPY app.py requirements.txt ./
 ---> c5d84c50c6d5
Step 3/4 : RUN python3.7 -m pip install -r requirements.txt -t .
 ---> Running in 57ecb24946b8
Collecting requests
  Downloading requests-2.26.0-py2.py3-none-any.whl (62 kB)
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.6-py2.py3-none-any.whl (138 kB)
Collecting certifi>=2017.4.17
  Downloading certifi-2021.5.30-py2.py3-none-any.whl (145 kB)
Collecting charset-normalizer~=2.0.0; python_version >= "3"
  Downloading charset_normalizer-2.0.3-py3-none-any.whl (35 kB)
Collecting idna<4,>=2.5; python_version >= "3"
  Downloading idna-3.2-py3-none-any.whl (59 kB)
Installing collected packages: urllib3, certifi, charset-normalizer, idna, requests
Successfully installed certifi-2021.5.30 charset-normalizer-2.0.3 idna-3.2 requests-2.26.0 urllib3-1.26.6
WARNING: You are using pip version 20.1.1; however, version 21.1.3 is available.
You should consider upgrading via the '/var/lang/bin/python3.7 -m pip install --upgrade pip' command.
 ---> 59b7e12078b4
Step 4/4 : CMD ["app.lambda_handler"]
 ---> Running in a7c7e1e83663
 ---> 998d9376380d
Successfully built 998d9376380d
Successfully tagged helloworldfunction:python3.7-v1

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

sam bulid後のdocker ps -a


$ docker ps -a
CONTAINER ID   IMAGE                         COMMAND                  CREATED         STATUS                     PORTS                                                 NAMES
a7c7e1e83663   59b7e12078b4                  "/lambda-entrypoint.…"   3 minutes ago   Created                                                                          heuristic_ramanujan
57ecb24946b8   c5d84c50c6d5                  "/bin/sh -c 'python3…"   3 minutes ago   Exited (0) 3 minutes ago                                                         exciting_mcnulty
ca95514c4b3b   6ac4a7a5270b                  "/lambda-entrypoint.…"   7 minutes ago   Created                                                                          festive_bohr
d0df56254002   1222cf864670                  "/bin/sh -c 'python3…"   7 minutes ago   Exited (0) 7 minutes ago                                                         dreamy_keller

sam bulid後のdocker images


$ docker images
REPOSITORY                     TAG            IMAGE ID       CREATED         SIZE
helloworldfunction             python3.7-v1   998d9376380d   3 minutes ago   905MB
helloworldfunction             python3.6-v1   4c3a691c319d   7 minutes ago   864MB
public.ecr.aws/lambda/python   3.6            452ed290a534   26 hours ago    862MB
public.ecr.aws/lambda/python   3.7            6cce156cc864   44 hours ago    902MB

続いてビルドしたコンテナイメージをECRにPUSH


$ aws ecr create-repository --repository-name helloworldfunction --image-tag-mutability MUTABLE --image-scanning-configuration scanOnPush=true
{
    "repository": {
        "repositoryArn": "arn:aws:ecr:ap-northeast-1:(AWS アカウント):repository/helloworldfunction",
        "registryId": "(AWS アカウント)",
        "repositoryName": "helloworldfunction",
        "repositoryUri": "(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction",
        "createdAt": "2021-07-18T18:42:09+09:00",
        "imageTagMutability": "MUTABLE",
        "imageScanningConfiguration": {
            "scanOnPush": true
        },
        "encryptionConfiguration": {
            "encryptionType": "AES256"
        }
    }
}

AWS ECRの画面確認

リポジトリが作成できたらログイン


$ aws ecr get-login-password  | docker login --username AWS --password-stdin (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com
Login Succeeded

ローカルのイメージにタグを付与してECRにPUSH


$ docker tag helloworldfunction:python3.7-v1 (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction:python3.7-v1

$ docker images
REPOSITORY                                                             TAG            IMAGE ID       CREATED          SIZE
(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction   python3.7-v1   998d9376380d   11 minutes ago   905MB
helloworldfunction                                                     python3.7-v1   998d9376380d   11 minutes ago   905MB
(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction   python3.6-v1   4c3a691c319d   16 minutes ago   864MB
helloworldfunction                                                     python3.6-v1   4c3a691c319d   16 minutes ago   864MB

$ docker push (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction:python3.7-v1
The push refers to repository [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]
0f2371243178: Pushed
7ee99c5cdb89: Pushed
a9e54df8bb45: Pushed
ecef42114359: Pushed
d6fa53d6caa6: Pushed
6a5f39160066: Pushed
48eb19332c1a: Pushed
652d3dccfc0e: Pushed
python3.7-v1: digest: sha256:1f50e8ae341ef4726c355a3cd7fbcfd060795a9540c80e842a6824947d03b1e3 size: 1999

SAM CLIでデプロイする

sam deploy –guided


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 [ap-northeast-1]:
        Image Repository for HelloWorldFunction [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]:
          helloworldfunction:python3.7-v1 to be pushed to (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction:helloworldfunction-ddfbf5a33f90-python3.7-v1

        #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: Found!

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-4l3kmmlghxba
                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

The push refers to repository [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]

0a748a1dff7d: Preparing 
7f4b8353559a: Preparing 
5554d5887065: Preparing 
5615f5a33a36: Preparing 
d6fa53d6caa6: Preparing 
854e7f8c528f: Preparing 
1373d8fe8d76: Preparing 
652d3dccfc0e: Preparing 
854e7f8c528f: Waiting 
652d3dccfc0e: Waiting 
1373d8fe8d76: Waiting 
5615f5a33a36: Layer already exists 
d6fa53d6caa6: Layer already exists 
0a748a1dff7d: Layer already exists 
5554d5887065: Layer already exists 
7f4b8353559a: Layer already exists 
854e7f8c528f: Layer already exists 
1373d8fe8d76: Layer already exists 
652d3dccfc0e: Layer already exists 
helloworldfunction-ddfbf5a33f90-python3.7-v1: digest: sha256:3e1ff8e37895fa639f3c029a7cbb1d0720db128d4901aec7a9860cbbc3130f02 size: 1999

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Deployment image repository  :
                                       {
                                           "HelloWorldFunction": "(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction"
                                       }
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-4l3kmmlghxba
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
File with same data already exists at sam-app/87bd0d6fceb06313e25e47eaccb328ba.template, skipping upload

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:(AWS アカウント):changeSet/samcli-deploy1626787896/074c180d-e72b-44a4-ab87-c77610b08c54

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

2021-07-20 22:31:51 - Waiting for stack create/update to complete

CloudFormation events from changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                             ResourceType                                               LogicalResourceId                                          ResourceStatusReason
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE_IN_PROGRESS                                         AWS::Lambda::Function                                      HelloWorldFunction                                         -
UPDATE_FAILED                                              AWS::Lambda::Function                                      HelloWorldFunction                                         Resource handler returned message: "Invalid request
                                                                                                                                                                                 provided: Updating PackageType is not supported"
                                                                                                                                                                                 (RequestToken: 50f08d5b-f635-6333-b29a-c44cfa112d7e,
                                                                                                                                                                                 HandlerErrorCode: InvalidRequest)
UPDATE_ROLLBACK_IN_PROGRESS                                AWS::CloudFormation::Stack                                 sam-app                                                    The following resource(s) failed to update:
                                                                                                                                                                                 [HelloWorldFunction].
UPDATE_COMPLETE                                            AWS::Lambda::Function                                      HelloWorldFunction                                         -
UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS               AWS::CloudFormation::Stack                                 sam-app                                                    -
UPDATE_ROLLBACK_COMPLETE                                   AWS::CloudFormation::Stack                                 sam-app                                                    -
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Error: Failed to create/update the stack: sam-app, Waiter StackUpdateComplete failed: Waiter encountered a terminal failure state: For expression "Stacks[].StackStatus" we matched expected path: "UPDATE_ROLLBACK_COMPLETE" at least once

C:\Users\youre\Documents\sam_test\sam-app>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 [ap-northeast-1]:
        Image Repository for HelloWorldFunction [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]:
          helloworldfunction:python3.7-v1 to be pushed to (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction:helloworldfunction-ddfbf5a33f90-python3.7-v1

        #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]: Y
        SAM configuration environment [default]: Aborted!
バッチ ジョブを終了しますか (Y/N)? Y

C:\Users\youre\Documents\sam_test\sam-app>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 [ap-northeast-1]:
        Image Repository for HelloWorldFunction [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]:
          helloworldfunction:python3.7-v1 to be pushed to (AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction:helloworldfunction-ddfbf5a33f90-python3.7-v1

        #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: Found!

                Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-4l3kmmlghxba
                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

The push refers to repository [(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction]

0a748a1dff7d: Preparing 
7f4b8353559a: Preparing 
5554d5887065: Preparing 
5615f5a33a36: Preparing 
d6fa53d6caa6: Preparing 
854e7f8c528f: Preparing 
1373d8fe8d76: Preparing 
652d3dccfc0e: Preparing 
854e7f8c528f: Waiting 
1373d8fe8d76: Waiting 
652d3dccfc0e: Waiting 
0a748a1dff7d: Layer already exists 
5615f5a33a36: Layer already exists 
5554d5887065: Layer already exists 
d6fa53d6caa6: Layer already exists 
7f4b8353559a: Layer already exists 
1373d8fe8d76: Layer already exists 
854e7f8c528f: Layer already exists 
652d3dccfc0e: Layer already exists 
helloworldfunction-ddfbf5a33f90-python3.7-v1: digest: sha256:3e1ff8e37895fa639f3c029a7cbb1d0720db128d4901aec7a9860cbbc3130f02 size: 1999

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Deployment image repository  :
                                       {
                                           "HelloWorldFunction": "(AWS アカウント).dkr.ecr.ap-northeast-1.amazonaws.com/helloworldfunction"
                                       }
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-4l3kmmlghxba
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
File with same data already exists at sam-app/87bd0d6fceb06313e25e47eaccb328ba.template, skipping upload

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:(AWS アカウント):changeSet/samcli-deploy1626788282/494daba4-ed91-4319-872d-290858cde67a

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

2021-07-20 22:38:15 - Waiting for stack create/update to complete

CloudFormation events from changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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_COMPLETE                                            AWS::ApiGateway::RestApi                                   ServerlessRestApi                                          -
CREATE_IN_PROGRESS                                         AWS::ApiGateway::RestApi                                   ServerlessRestApi                                          Resource creation Initiated
CREATE_IN_PROGRESS                                         AWS::Lambda::Permission                                    HelloWorldFunctionHelloWorldPermissionProd                 Resource creation Initiated
CREATE_IN_PROGRESS                                         AWS::ApiGateway::Deployment                                ServerlessRestApiDeployment47fc2d5f9d                      -
CREATE_IN_PROGRESS                                         AWS::Lambda::Permission                                    HelloWorldFunctionHelloWorldPermissionProd                 -
CREATE_IN_PROGRESS                                         AWS::ApiGateway::Stage                                     ServerlessRestApiProdStage                                 -
CREATE_COMPLETE                                            AWS::ApiGateway::Deployment                                ServerlessRestApiDeployment47fc2d5f9d                      -
CREATE_IN_PROGRESS                                         AWS::ApiGateway::Deployment                                ServerlessRestApiDeployment47fc2d5f9d                      Resource creation Initiated
CREATE_COMPLETE                                            AWS::ApiGateway::Stage                                     ServerlessRestApiProdStage                                 -
CREATE_IN_PROGRESS                                         AWS::ApiGateway::Stage                                     ServerlessRestApiProdStage                                 Resource creation Initiated
CREATE_COMPLETE                                            AWS::Lambda::Permission                                    HelloWorldFunctionHelloWorldPermissionProd                 -
CREATE_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::(AWS アカウント):role/sam-app-HelloWorldFunctionRole-QTGXZAM1VIVA

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

Key                 HelloWorldFunction
Description         Hello World Lambda Function ARN
Value               arn:aws:lambda:ap-northeast-1:(AWS アカウント):function:sam-app-HelloWorldFunction-7T9Nq24qJXRc
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

Error


Error: Failed to create/update the stack: sam-tweepy, Waiter StackCreateComplete failed: Waiter encountered a terminal failure state: For expression "Stacks[].StackStatus" we matched expected path: "ROLLBACK_COMPLETE" at least once

Error: Failed to create changeset for the stack: sam-tweepy, An error occurred (ValidationError) when calling the CreateChangeSet operation: Stack:arn:aws:cloudformation:ap-northeast-1:(AWS アカウント):stack/sam-tweepy/cfbdf6e0-e7a7-11eb-932e-0e10ba58e8a3 is in ROLLBACK_COMPLETE state and can not be updated.

エラーの場合、CloudFormationのスタックに内容が表示されている。 再実行する場合、エラーとなっているスタックを削除して、再実行すると正常に完了する。

タイトルとURLをコピーしました