1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS SAMでサーバレスアプリケーションを作ってみる

Posted at

こんにちは。
株式会社クラスアクト インフラストラクチャ事業部の大塚です。

今回はSAMについて実際に試してみたいと思います。
最近DVAの取得の為勉強しているのですが、割と見るので触っておきます。

参考サイトは公式より

SAMとは

AWS SAM(Serverless Application Model)は、AWSが提供するフレームワークで、サーバーレスアプリケーションの開発、デプロイ、管理を簡素化するために設計されています。SAMを使用することで、開発者はAWS Lambda、API Gateway、DynamoDBなどのサーバーレスリソースを簡単に定義し、デプロイすることができます。

環境イメージ

今回はCloudShellでSAM関連の操作を行い、デプロイしていきたいと思います。

growi-ページ39.drawio.png

構築

AWS CloudShellで色々試してみます。pythonとsam-cliのバージョンを確認します。

Commands:
~ $ python --version
Python 3.9.21
~ $ sam --version
SAM CLI, version 1.136.0

image (17).png

sam initコマンドを実行してCloudShellのローカルにプロジェクトを作成します。
コンソール上にpython3.13で良いかと出力されますが、ローカルはpython3.9なので、合わせます。

~ $ 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 - GraphQLApi Hello World Example
        11 - Full Stack
        12 - Lambda EFS example
        13 - Serverless Connector Hello World Example
        14 - Multi-step workflow with Connectors
        15 - DynamoDB Example
        16 - Machine Learning
Template: 1

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

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - go (provided.al2)
        4 - go (provided.al2023)
        5 - graalvm.java11 (provided.al2)
        6 - graalvm.java17 (provided.al2)
        7 - java21
        8 - java17
        9 - java11
        10 - java8.al2
        11 - nodejs22.x
        12 - nodejs20.x
        13 - nodejs18.x
        14 - python3.9
        15 - python3.13
        16 - python3.12
        17 - python3.11
        18 - python3.10
        19 - ruby3.4
        20 - ruby3.3
        21 - ruby3.2
        22 - rust (provided.al2)
        23 - rust (provided.al2023)
Runtime: 14

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

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
    Base Image: amazon/python3.9-base
    Architectures: x86_64
    Dependency Manager: pip
    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.139.0); (1.136.0 installed)
To download: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html

カレントディレクトリに様々なフォルダが作成されていることがわかる。

~ $ ls -ltR
.:
total 4
drwxr-xr-x. 5 cloudshell-user cloudshell-user 4096 May 31 06:18 sam-app

./sam-app:
total 28
-rw-r--r--. 1 cloudshell-user cloudshell-user  682 May 31 06:18 samconfig.toml
-rw-r--r--. 1 cloudshell-user cloudshell-user 2495 May 31 06:18 template.yaml
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 events
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 hello_world
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:18 tests
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py
-rw-r--r--. 1 cloudshell-user cloudshell-user 6870 May 31 06:18 README.md

./sam-app/events:
total 4
-rw-r--r--. 1 cloudshell-user cloudshell-user 2092 May 31 06:18 event.json

./sam-app/hello_world:
total 12
-rw-r--r--. 1 cloudshell-user cloudshell-user 892 May 31 06:18 app.py
-rw-r--r--. 1 cloudshell-user cloudshell-user 250 May 31 06:18 Dockerfile
-rw-r--r--. 1 cloudshell-user cloudshell-user   0 May 31 06:18 __init__.py
-rw-r--r--. 1 cloudshell-user cloudshell-user   8 May 31 06:18 requirements.txt

./sam-app/tests:
total 4
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 unit
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py

./sam-app/tests/unit:
total 4
-rw-r--r--. 1 cloudshell-user cloudshell-user 2535 May 31 06:18 test_handler.py
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py

以下のファイルが重要とのこと。

  • hello_world/app.py – Lambda 関数コードが含まれます。
  • hello_world/requirements.txt – Lambda 関数に必要な Python 依存関係が含まれます。
    samconfig.toml – で使用されるデフォルトのパラメータを保存するアプリケーションの設定ファイル AWS SAMCLI。
  • template.yaml – アプリケーションインフラストラクチャコードを含む AWS SAM テンプレート。

実際のファイルを見てみる。
app.pyはLambdaでよく見るもの。

app.py
import json

# import requests


def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    # try:
    #     ip = requests.get("http://checkip.amazonaws.com/")
    # except requests.RequestException as e:
    #     # Send some context about this error to Lambda Logs
    #     print(e)

    #     raise e

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            # "location": ip.text.replace("\n", "")
        }),
    }

Dockerfileの中身

FROM public.ecr.aws/lambda/python:3.9

COPY requirements.txt ./
RUN python3.9 -m pip install -r requirements.txt -t .

COPY app.py ./

# Command can be overwritten by providing a different command in the template directly.
CMD ["app.lambda_handler"]

template.yamlの中身。
SAMはCFNの拡張のようなので似ていますね。

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  python3.11

  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

    Tracing: Active
    # You can add LoggingConfig parameters such as the Logformat, Log Group, and SystemLogLevel or ApplicationLogLevel. Learn more here https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-loggingconfig.
    LoggingConfig:
      LogFormat: JSON
  Api:
    TracingEnabled: true
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:
      PackageType: Image
      Architectures:
      - x86_64
      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
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: python3.11-v1

  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Sub: ApplicationInsights-SAM-${AWS::StackName}
      ResourceQuery:
        Type: CLOUDFORMATION_STACK_1_0
  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Ref: ApplicationResourceGroup
      AutoConfigurationEnabled: 'true'
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

sam buildを実行してサーバーレスアプリケーションのソースコードをビルドして、デプロイ可能な状態にするためのプロセスを実行する

sam-app $ sam build
Building codeuri: /home/cloudshell-user/sam-app runtime: None architecture: x86_64 functions: HelloWorldFunction                                                                                                                                                        
Building image for HelloWorldFunction function                                                                                                                                                                                                                          
Setting DockerBuildArgs for HelloWorldFunction function                                                                                                                                                                                                                 

Step 1/5 : FROM public.ecr.aws/lambda/python:3.9
3.9: Pulling from lambda/python 
c37dca5e3df2: Pull complete 
51d480c7355c: Pull complete 
ec5820170ae2: Pull complete 
e2ef3e53683d: Pull complete 
0147022c5310: Pull complete 
37ab31843e2e: Pull complete 
Status: Downloaded newer image for public.ecr.aws/lambda/python:3.9 ---> ff8a64315668
Step 2/5 : COPY requirements.txt ./
 ---> 66dcc21373ca
Step 3/5 : RUN python3.9 -m pip install -r requirements.txt -t .
 ---> Running in 97c05d12e067
Collecting requests
  Downloading requests-2.32.3-py3-none-any.whl (64 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 64.9/64.9 kB 6.7 MB/s eta 0:00:00
Collecting certifi>=2017.4.17
  Downloading certifi-2025.4.26-py3-none-any.whl (159 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 159.6/159.6 kB 22.1 MB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1
  Downloading urllib3-2.4.0-py3-none-any.whl (128 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 128.7/128.7 kB 21.1 MB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
  Downloading charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (149 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 149.5/149.5 kB 20.4 MB/s eta 0:00:00
Collecting idna<4,>=2.5
  Downloading idna-3.10-py3-none-any.whl (70 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 70.4/70.4 kB 10.5 MB/s eta 0:00:00
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2025.4.26 charset-normalizer-3.4.2 idna-3.10 requests-2.32.3 urllib3-2.4.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

[notice] A new release of pip is available: 23.0.1 -> 25.1.1
[notice] To update, run: pip install --upgrade pip
 ---> Removed intermediate container 97c05d12e067
 ---> c4712120b9e8
Step 4/5 : COPY app.py ./
 ---> ea57a620d81a
Step 5/5 : CMD ["app.lambda_handler"]
 ---> Running in 8b12ea89e520
 ---> Removed intermediate container 8b12ea89e520
 ---> 7b20b931f608
Successfully built 7b20b931f608
Successfully tagged helloworldfunction:python3.9-v1


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 {{stack-name}} --watch
[*] Deploy: sam deploy --guided

buildというディレクトリが、隠しディレクト配下に存在していますね。

sam-app $ ls -ltaR
.:
total 44
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:20 .aws-sam
drwxr-xr-x. 6 cloudshell-user cloudshell-user 4096 May 31 06:20 .
-rw-r--r--. 1 cloudshell-user cloudshell-user  682 May 31 06:18 samconfig.toml
-rw-r--r--. 1 cloudshell-user cloudshell-user 2495 May 31 06:18 template.yaml
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 events
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 hello_world
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:18 tests
-rw-r--r--. 1 cloudshell-user cloudshell-user 3730 May 31 06:18 .gitignore
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py
-rw-r--r--. 1 cloudshell-user cloudshell-user 6870 May 31 06:18 README.md
drwxrwxrwx. 7 cloudshell-user cloudshell-user 4096 May 31 06:18 ..

./.aws-sam:
total 16
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:23 build
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:20 .
-rw-r--r--. 1 cloudshell-user cloudshell-user  395 May 31 06:20 build.toml
drwxr-xr-x. 6 cloudshell-user cloudshell-user 4096 May 31 06:20 ..

./.aws-sam/build:
total 12
-rw-r--r--. 1 cloudshell-user cloudshell-user 1720 May 31 06:23 template.yaml
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:23 .
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:20 ..

./events:
total 12
drwxr-xr-x. 6 cloudshell-user cloudshell-user 4096 May 31 06:20 ..
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 .
-rw-r--r--. 1 cloudshell-user cloudshell-user 2092 May 31 06:18 event.json

./hello_world:
total 20
drwxr-xr-x. 6 cloudshell-user cloudshell-user 4096 May 31 06:20 ..
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 .
-rw-r--r--. 1 cloudshell-user cloudshell-user  892 May 31 06:18 app.py
-rw-r--r--. 1 cloudshell-user cloudshell-user  250 May 31 06:18 Dockerfile
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py
-rw-r--r--. 1 cloudshell-user cloudshell-user    8 May 31 06:18 requirements.txt

./tests:
total 12
drwxr-xr-x. 6 cloudshell-user cloudshell-user 4096 May 31 06:20 ..
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 unit
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:18 .
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py

./tests/unit:
total 12
drwxr-xr-x. 2 cloudshell-user cloudshell-user 4096 May 31 06:18 .
-rw-r--r--. 1 cloudshell-user cloudshell-user 2535 May 31 06:18 test_handler.py
drwxr-xr-x. 3 cloudshell-user cloudshell-user 4096 May 31 06:18 ..
-rw-r--r--. 1 cloudshell-user cloudshell-user    0 May 31 06:18 __init__.py

SAMテンプレートの検証を以下のコマンドで実行する
問題なさそう。

sam-app $ sam validate
/home/cloudshell-user/sam-app/template.yaml is a valid SAM Template

ローカル環境で関数を呼び出してみる
ステータスコードが200のものが返ってきているので問題なさそう
内部的にはdockerコンテナを使っているっぽい。

sam-app $ sam local invoke
Invoking Container created from helloworldfunction:python3.9-v1                                                                                                                                                                                                         
Local image was not found.                                                                                                                                                                                                                                              
Removing rapid images for repo helloworldfunction                                                                                                                                                                                                                 
Building image.................
Using local image: helloworldfunction:rapid-x86_64.                                        

START RequestId: 583a857e-a9c4-4c21-980d-6a74dc7aec2a Version: $LATEST
END RequestId: b6496145-fbff-42c1-9c2c-e5651ddd3882
REPORT RequestId: b6496145-fbff-42c1-9c2c-e5651ddd3882  Init Duration: 0.06 ms  Duration: 181.98 ms     Billed Duration: 182 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

デプロイしていく。

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]: 
        #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
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: Y
        HelloWorldFunction has no authentication. 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:
        Creating the required resources...
        Successfully created!

        Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-59fn6v7fk3f4
        A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False
                                                                                                                                                                                                                                                                        
        Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].                                                                                                                                     
        This parameter will be only saved under [default.global.parameters] in /home/cloudshell-user/sam-app/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

44ea107c8fcb: Pushed 
68647e94abbd: Pushed 
1076fda1b422: Pushed 
b07d597978b2: Pushed 
494fc5cd1f64: Pushed 
6a9b57324378: Pushed 
887ce20b74f9: Pushed 
6b2a0fd03dc9: Pushed 
f4b46dc2d7e0: Pushed 
helloworldfunction-7b20b931f608-python3.9-v1: digest: sha256:92b218f0c57d24058b32b2c6ad2488360ad673620657c770928e7dc7f7d0074f size: 2206

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : ap-northeast-1
        Confirm changeset            : True
        Disable rollback             : True
        Deployment image repository  : 
                                       {
                                           "HelloWorldFunction": "535002847634.dkr.ecr.ap-northeast-1.amazonaws.com/samapp7427b055/helloworldfunction19d43fc4repo"
                                       }
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-59fn6v7fk3f4
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

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

HelloWorldFunction has no authentication.
        Uploading to sam-app/7dc3b9c67dd341b2d4aa4c79ae1614e9.template  1954 / 1954  (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                                                             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:535002847634:changeSet/samcli-deploy1748675337/5fcb0b9d-071d-4f4c-8b77-d82ddcc9f1db


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

2025-05-31 07:09:09 - 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_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::Lambda::Permission                                           HelloWorldFunctionHelloWorldPermissionProd                        -                                                               
CREATE_IN_PROGRESS                                                AWS::ApiGateway::Deployment                                       ServerlessRestApiDeployment47fc2d5f9d                             -                                                               
CREATE_IN_PROGRESS                                                AWS::Lambda::Permission                                           HelloWorldFunctionHelloWorldPermissionProd                        Resource creation Initiated                                     
CREATE_IN_PROGRESS                                                AWS::ApiGateway::Deployment                                       ServerlessRestApiDeployment47fc2d5f9d                             Resource creation Initiated                                     
CREATE_COMPLETE                                                   AWS::Lambda::Permission                                           HelloWorldFunctionHelloWorldPermissionProd                        -                                                               
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::ApplicationInsights::Application                             ApplicationInsightsMonitoring                                     -                                                               
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::535002847634:role/sam-app-HelloWorldFunctionRole-BPPukNpb4kDk                                                                                                                                                                      

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

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


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

マネコンでCFNのスタックを見てみると、SAMでデプロイしたものが表示されている。
image (18).png

LambdaもAPIゲートウェイに紐づいた状態でデプロイされている。
image (19).png

SAMでデプロイしている為、Lambdaのコードはここでは見れない様子。
image (20).png

APIを叩いてみる。問題なさそう。
image (21).png
image (22).png

ECRにリポジトリを作ってコンテナイメージをプッシュしていることもわかる。このイメージを使ってLambda関数がデプロイされている。
image (23).png
S3にデプロイパッケージやバージョン管理のための配置をしていることもわかる。
image (24).png

削除するためには以下のコマンドを実行する。
S3バケットが削除できていないようす。

sam-app $ sam delete --stack-name sam-app
        Are you sure you want to delete the stack sam-app in the region ap-northeast-1 ? [y/N]: y
        Found ECR Companion Stack sam-app-7427b055-CompanionStack
        Do you want to delete the ECR companion stack sam-app-7427b055-CompanionStack in the region ap-northeast-1 ? [y/N]: y
        ECR repository samapp7427b055/helloworldfunction19d43fc4repo may not be empty. Do you want to delete the repository and all the images in it ? [y/N]: y
        - Deleting ECR repository samapp7427b055/helloworldfunction19d43fc4repo
        - Deleting ECR Companion Stack sam-app-7427b055-CompanionStack
        - Deleting Cloudformation stack sam-app

Warning: Cannot resolve s3 bucket information from command options , local config file or cloudformation template. Please use --s3-bucket next time and delete s3 files manually if required.

Deleted successfully

CFNやS3を見てみると確かに残っているように見えるので、こちらから削除しておく
image (25).png
image (26).png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?