- 公開日
- 最終更新日
【SAM】最新の状態を自動で反映したい
この記事を共有する
はじめに
パーソル&サーバーワークスの嶋田です。
SAMを使って開発をしていると、sam build / sam deploy コマンドはよく使いますよね。
でも、ちょっとした修正ごとにこのサイクルを回すのは少々面倒だと感じませんか?
そんなあなたに、sam sync コマンドのご紹介です。
sam sync とは
sam sync コマンドは、ローカルのアプリケーションの変更をAWSクラウドに同期する。
公式には上記の通り書かれていますが、もう少し具体化すると、
SAMテンプレートや、SAMでデプロイしているコードの変更を、タイムリーに自動適用してくれます。
本ブログを通じて、実際の動作を見てみましょう。
手順
環境構築
SAMプロジェクトの初期化
$ sam init
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.8
16 - python3.13
17 - python3.12
18 - python3.11
19 - python3.10
20 - ruby3.3
21 - ruby3.2
22 - rust (provided.al2)
23 - rust (provided.al2023)
Runtime: 12
What package type would you like to use?
1 - Zip
2 - Image
Package type: 1
Based on your selections, the only dependency manager available is npm.
We will proceed copying the template using npm.
Select your starter template
1 - Hello World Example
2 - Hello World Example TypeScript
Template: 1
Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]:
Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]:
Would you like to set Structured Logging in JSON format on your Lambda functions? [y/N]:
Project name [sam-app]:
-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: nodejs20.x
Architectures: x86_64
Dependency Manager: npm
Application Template: hello-world
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プロジェクトのディレクトリに移動
$ cd sam-app/
ビルド実行
$ sam build
Starting Build use cache
Manifest file is changed (new hash: c0e83ff3ce1bd02a0c2a7c02974c24ec) or dependency folder
(.aws-sam/deps/47a69bbc-ac32-4fad-93e0-932c9b3b06d3) is missing for (HelloWorldFunction), downloading
dependencies and copying/building source
Building codeuri: /home/ec2-user/Developments/sam-app/hello-world runtime: nodejs20.x architecture: x86_64
functions: HelloWorldFunction
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrcAndLockfile
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUp
Running NodejsNpmBuilder:CopyDependencies
Running NodejsNpmBuilder:CleanUpNpmrc
Running NodejsNpmBuilder:LockfileCleanUp
Running NodejsNpmBuilder:LockfileCleanUp
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
アプリケーションデプロイ
$ sam deploy
Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-0jsdlxcilt06
A different default S3 bucket can be set in samconfig.toml
Or by specifying --s3-bucket explicitly.
Uploading to 7ce1f134cb26788817fd18fb91dfdd72 798845 / 798845 (100.00%)
Deploying with following values
===============================
Stack name : sam-app
Region : ap-northeast-1
Confirm changeset : True
Disable rollback : False
Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-0jsdlxcilt06
Capabilities : ["CAPABILITY_IAM"]
Parameter overrides : {}
Signing Profiles : {}
Initiating deployment
=====================
Uploading to b7c8424df66e30d7627b161ca658d08f.template 1171 / 1171 (100.00%)
Waiting for changeset to be created..
CloudFormation stack changeset
-----------------------------------------------------------------------------------------------------
Operation LogicalResourceId ResourceType Replacement
-----------------------------------------------------------------------------------------------------
+ Add HelloWorldFunctionHello AWS::Lambda::Permission N/A
WorldPermissionProd
+ Add HelloWorldFunctionRole AWS::IAM::Role N/A
+ Add HelloWorldFunction AWS::Lambda::Function N/A
+ Add ServerlessRestApiDeploy AWS::ApiGateway::Deploy N/A
ment47fc2d5f9d ment
+ Add ServerlessRestApiProdSt AWS::ApiGateway::Stage N/A
age
+ Add ServerlessRestApi AWS::ApiGateway::RestAp N/A
i
-----------------------------------------------------------------------------------------------------
Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:012345678910:changeSet/samcli-deploy1739714042/6c8697d6-ee94-44f2-904d-a9f482f22b9a
Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y
2025-02-16 14:18:33 - 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::St sam-app User Initiated
ack
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_IN_PROGRESS - AWS::Lambda::Function HelloWorldFunction Eventual consistency
CONFIGURATION_COMPLETE check initiated
CREATE_IN_PROGRESS AWS::ApiGateway::RestAp ServerlessRestApi -
i
CREATE_IN_PROGRESS AWS::ApiGateway::RestAp ServerlessRestApi Resource creation
i Initiated
CREATE_COMPLETE AWS::ApiGateway::RestAp ServerlessRestApi -
i
CREATE_IN_PROGRESS AWS::ApiGateway::Deploy ServerlessRestApiDeploy -
ment ment47fc2d5f9d
CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHello -
WorldPermissionProd
CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHello Resource creation
WorldPermissionProd Initiated
CREATE_IN_PROGRESS AWS::ApiGateway::Deploy ServerlessRestApiDeploy Resource creation
ment ment47fc2d5f9d Initiated
CREATE_COMPLETE AWS::Lambda::Permission HelloWorldFunctionHello -
WorldPermissionProd
CREATE_COMPLETE AWS::ApiGateway::Deploy ServerlessRestApiDeploy -
ment ment47fc2d5f9d
CREATE_COMPLETE AWS::Lambda::Function HelloWorldFunction -
CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdSt -
age
CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdSt Resource creation
age Initiated
CREATE_COMPLETE AWS::ApiGateway::Stage ServerlessRestApiProdSt -
age
CREATE_COMPLETE AWS::CloudFormation::St sam-app -
ack
-----------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
--------------------------------------------------------------------------------------------------------
Outputs
--------------------------------------------------------------------------------------------------------
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-MIiCJTpt1YUh
Key HelloWorldApi
Description API Gateway endpoint URL for Prod stage for Hello World function
Value https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:ap-northeast-1:012345678910:function:sam-app-HelloWorldFunction-
pnVv84KNnPNc
--------------------------------------------------------------------------------------------------------
Successfully created/updated stack - sam-app in ap-northeast-1
API Gatewayの動作確認
$ curl https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message":"hello world"}
アプリケーションコードの確認
$ cat ./hello-world/app.mjs
/**
*
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
* @param {Object} event - API Gateway Lambda Proxy Input Format
*
* Context doc: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
* @param {Object} context
*
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
* @returns {Object} object - API Gateway Lambda Proxy Output Format
*
*/
export const lambdaHandler = async (event, context) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello world',
})
};
return response;
};
sam sync を使ってみる
sam sync を使う環境が整ったので、実際に使っていきます。
$ sam sync The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without performing a CloudFormation deployment. This will cause drift in your CloudFormation stack. **The sync command should only be used against a development stack**. Confirm that you are synchronizing a development stack. Enter Y to proceed with the command, or enter N to cancel: [Y/n]: Y Queued infra sync. Waiting for in progress code syncs to complete... Starting infra sync. Manifest is not changed for (HelloWorldFunction), running incremental build Building codeuri: /home/ec2-user/Developments/sam-app/hello-world runtime: nodejs20.x architecture: x86_64 functions: HelloWorldFunction Running NodejsNpmBuilder:NpmPack Running NodejsNpmBuilder:CopyNpmrcAndLockfile Running NodejsNpmBuilder:CopySource Running NodejsNpmBuilder:CleanUpNpmrc Running NodejsNpmBuilder:LockfileCleanUp Running NodejsNpmBuilder:LockfileCleanUp Build Succeeded Successfully packaged artifacts and wrote output template to file /tmp/tmpa4ktlriz. Execute the following command to deploy the packaged template sam deploy --template-file /tmp/tmpa4ktlriz --stack-nameDeploying with following values =============================== Stack name : sam-app Region : ap-northeast-1 Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-0jsdlxcilt06 Capabilities : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"] Parameter overrides : {} Signing Profiles : null Initiating deployment ===================== 2025-02-16 14:40:20 - Waiting for stack create/update to complete CloudFormation events from stack operations (refresh every 0.5 seconds) ------------------------------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason ------------------------------------------------------------------------------------------------------------------------------------------------------------- UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app User Initiated UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app Transformation succeeded CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedStack - CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedStack Resource creation Initiated CREATE_COMPLETE AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedStack - 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::012345678910:role/sam-app-HelloWorldFunctionRole-MIiCJTpt1YUh Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:ap-northeast-1:012345678910:function:sam-app-HelloWorldFunction-pnVv84KNnPNc ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Stack update succeeded. Sync infra completed. CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi. Infra sync completed.
Infra sync completed. と表示されていれば完了です。
コードを書き換えてみる
例えば、現在の hello world の結果を返すAPIを、
hello sam の結果を返すように、コードを書き換えます。
$ cat ./hello-world/app.mjs
/**
*
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
* @param {Object} event - API Gateway Lambda Proxy Input Format
*
* Context doc: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
* @param {Object} context
*
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
* @returns {Object} object - API Gateway Lambda Proxy Output Format
*
*/
export const lambdaHandler = async (event, context) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello sam',
})
};
return response;
};
コードを書き換えると、以下のように sam sync のCLIに動きが見えます。
Syncing Lambda Function HelloWorldFunction... Manifest is not changed for (HelloWorldFunction), running incremental build Building codeuri: /home/ec2-user/Developments/sam-app/hello-world runtime: nodejs20.x architecture: x86_64 functions: HelloWorldFunction Running NodejsNpmBuilder:NpmPack Running NodejsNpmBuilder:CopyNpmrcAndLockfile Running NodejsNpmBuilder:CopySource Running NodejsNpmBuilder:CleanUpNpmrc Running NodejsNpmBuilder:LockfileCleanUp Running NodejsNpmBuilder:LockfileCleanUp SyncFlow [Lambda Function HelloWorldFunction]: Skipping resource update as the content didn't change 16/Feb/2025:14:46:00: Finished syncing Lambda Function HelloWorldFunction.
Finished syncing Lambda Function HelloWorldFunction. と出ていますね。
同期が完了したようです。
APIを再度実行してみる
$ curl https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message":"hello sam"}
hello sam と応答してくれてますね。
このように、sam build sam deploy せずとも動的に最新のコードを反映してくれます。
CloudFormationリソースについても、同様に反映してくれます。
こちらの動作も確認してみましょう。
リソースを追加してみる
まず、既存のhello-worldアプリケーションを複製します。
$ cp -r ./hello-world ./hello-sam-world
続いて、複製したアプリケーションのreturnを、 hello sam から hello sam world に書き換えます。
/**
*
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
* @param {Object} event - API Gateway Lambda Proxy Input Format
*
* Context doc: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
* @param {Object} context
*
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
* @returns {Object} object - API Gateway Lambda Proxy Output Format
*
*/
export const lambdaHandler = async (event, context) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello sam world',
})
};
return response;
};
最後に、template.ymlを書き換えて、今回追加した hello sam world を返すAPIを追加します。
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.lambdaHandler
Runtime: nodejs20.x
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
HelloSamWorldFunction:
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-sam-world/
Handler: app.lambdaHandler
Runtime: nodejs20.x
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-sam
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
HelloSamWorldFunction が追加したブロックです。
sam sync のCLIを確認してみます。
Starting infra sync. Manifest file is changed (new hash: c0e83ff3ce1bd02a0c2a7c02974c24ec) or dependency folder (.aws-sam/deps/4f8d10f1-63ab-459a-b3ec-ce9d38cd8b6e) is missing for (HelloSamWorldFunction), downloading dependencies and copying/building source Manifest is not changed for (HelloWorldFunction), running incremental build Building codeuri: /home/ec2-user/Developments/sam-app/hello-world runtime: nodejs20.x architecture: x86_64 functions: HelloWorldFunction Building codeuri: /home/ec2-user/Developments/sam-app/hello-sam-world runtime: nodejs20.x architecture: x86_64 functions: HelloSamWorldFunction Running NodejsNpmBuilder:NpmPack Running NodejsNpmBuilder:NpmPack Running NodejsNpmBuilder:CopyNpmrcAndLockfile Running NodejsNpmBuilder:CopySource Running NodejsNpmBuilder:CleanUpNpmrc Running NodejsNpmBuilder:LockfileCleanUp Running NodejsNpmBuilder:LockfileCleanUp Running NodejsNpmBuilder:CopyNpmrcAndLockfile Running NodejsNpmBuilder:CopySource Running NodejsNpmBuilder:NpmInstall Running NodejsNpmBuilder:CleanUp Running NodejsNpmBuilder:MoveDependencies Running NodejsNpmBuilder:CleanUpNpmrc Running NodejsNpmBuilder:LockfileCleanUp Running NodejsNpmBuilder:LockfileCleanUp Build Succeeded Successfully packaged artifacts and wrote output template to file /tmp/tmpgmjmk3fz. Execute the following command to deploy the packaged template sam deploy --template-file /tmp/tmpgmjmk3fz --stack-nameDeploying with following values =============================== Stack name : sam-app Region : ap-northeast-1 Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-0jsdlxcilt06 Capabilities : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"] Parameter overrides : {} Signing Profiles : null Initiating deployment ===================== 2025-02-16 15:13:12 - Waiting for stack create/update to complete CloudFormation events from stack operations (refresh every 0.5 seconds) ----------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason ----------------------------------------------------------------------------------------------------------------------------------------- UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app User Initiated UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app Transformation succeeded CREATE_IN_PROGRESS AWS::IAM::Role HelloSamWorldFunctionRole - UPDATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedS - tack CREATE_IN_PROGRESS AWS::IAM::Role HelloSamWorldFunctionRole Resource creation Initiated UPDATE_COMPLETE AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedS - tack CREATE_COMPLETE AWS::IAM::Role HelloSamWorldFunctionRole - CREATE_IN_PROGRESS AWS::Lambda::Function HelloSamWorldFunction - CREATE_IN_PROGRESS AWS::Lambda::Function HelloSamWorldFunction Resource creation Initiated CREATE_COMPLETE AWS::Lambda::Function HelloSamWorldFunction - UPDATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi - UPDATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi - CREATE_IN_PROGRESS AWS::Lambda::Permission HelloSamWorldFunctionHelloWorldP - ermissionProd CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment33eaa - 52b2d CREATE_IN_PROGRESS AWS::Lambda::Permission HelloSamWorldFunctionHelloWorldP Resource creation Initiated ermissionProd CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment33eaa Resource creation Initiated 52b2d CREATE_COMPLETE AWS::Lambda::Permission HelloSamWorldFunctionHelloWorldP - ermissionProd CREATE_COMPLETE AWS::ApiGateway::Deployment ServerlessRestApiDeployment33eaa - 52b2d UPDATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage - UPDATE_COMPLETE AWS::ApiGateway::Stage ServerlessRestApiProdStage - UPDATE_COMPLETE_CLEANUP_IN_PROGR AWS::CloudFormation::Stack sam-app - ESS DELETE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2 - d5f9d DELETE_COMPLETE AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2 - d5f9d UPDATE_COMPLETE AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedS - tack 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::012345678910:role/sam-app-HelloWorldFunctionRole-MIiCJTpt1YUh Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:ap-northeast-1:012345678910:function:sam-app-HelloWorldFunction-pnVv84KNnPNc ------------------------------------------------------------------------------------------------------------------------------------------- Stack update succeeded. Sync infra completed. CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi. Infra sync completed.
設定も反映されていそうですね。実際に動きを確認してみましょう。
追加したリソースにGETリクエストを送る
$ curl https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello-sam/
{"message":"hello sam world"}
しっかり反映されていますね。念のため元のAPIも実行して、リソースの上書きではなく、追加されていることを確認します。
$ curl https://xfk8gt8fk5.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
{"message":"hello sam"}
従来のAPIも動作していますね。 最後に、不要なリソースを削除して終了します。
リソースの削除
$ sam delete
Are you sure you want to delete the stack sam-app in the region ap-northeast-1 ? [y/N]: y
Do you want to delete the template file d798178a22d31650a38c00e9b03fbfd4.template in S3? [y/N]: y
- Deleting S3 object with key baeb42c8dde2192f2f9925a991a81f19
- Deleting S3 object with key b62f7776048ddee679d04d5a3649185a
- Deleting S3 object with key 0c4e696f3725f5e99297e02552b2535b.template
- Deleting S3 object with key d798178a22d31650a38c00e9b03fbfd4.template
- Deleting Cloudformation stack sam-app
Deleted successfully
$ cd ../
$ rm -rf sam-app/
以上です。お疲れさまでした。
この記事は私が書きました
嶋田 龍登
記事一覧インフラからアプリのことまでなんでもやりたい、フルスタックを目指すエンジニア