Amazon SAMについて勉強中
Amazon SAMについて
急遽勉強中。
Amazon SAMのSAMはServerless Application Modelの略です。
EC2とかElasticBeansTalkとか使わずにWebAPI作って動かしたりします。
中身はLambdaなんで API Gateway + Lambda でいけるじゃん?と思いましたが。
ローカルでLambdaの実行環境作ってくれるし、RDSとかS3とかの環境もCloudFormationで作ってくれたりします、後は検証環境・本番環境などを分けてデプロイする仕組みも提供してくれるので割と至れり尽くせりです。
実際の中身は、
- CloudFormation
- API Gateway
- Lambda
- IAMのルール
を混ぜたものって考えればいいのかな。
- API Gateway・・・一応わかる。
- Lambda・・・一回作ったことはある。
- IAM・・・まぁ大丈夫だろう。
- CloudFormation・・・わからない。
AWSにかな疎いところが暴露されちゃうわけですが。
最初に
Amazon SAMを使う場合はAccess KeyとSecret Access Keyが必要です。
IAMでユーザー作って発行しましょう。
更に AWS CLIも必要です。インストールしときましょう。
アカウント複数持ってたら「AWS CLIでユーザー切り替え」で切り替えときましょう。
この後SAM CLIのサンプルHelloWorld作ったりしますが。
それをデプロイするにはIAMユーザーに以下のポリシーが必要なので追加しておきましょう。
AWSCloudFormationFullAccess
IAMFullAccess
AWSLambda_FullAccess
AmazonAPIGatewayAdministrator
AmazonS3FullAccess
AmazonEC2ContainerRegistryFullAccess
これはSAMをデプロイするユーザーに最低限必要なポリシーになります。
SAM CLIインストール
Amazon SAM自体はコマンドラインインターフェースが提供されてて SAM CLI インストールすれば使えました。
SAM CLIでアプリケーション作ると上記の纏めた雛形を作ってくれます。
そしてビルド・デプロイまでSAM CLIが面倒見てくれます。
Hello World
サンプルでHello Worldがあるので実際作ってみるとこんな感じ。
$ 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 ←■AWS Quick Start Templatesを選択
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 - Serverless Connector Hello World Example
11 - Multi-step workflow with Connectors
12 - GraphQLApi Hello World Example
13 - Full Stack
14 - Lambda EFS example
15 - Hello World Example With Powertools for AWS Lambda
16 - DynamoDB Example
17 - Machine Learning
Template: 1 ←■Hello World Exampleを選択
Use the most popular runtime and package type? (Python and zip) [y/N]: Y ←■YにしてPython and zipの基本パターンを選択
Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: ←■そのままEnterでX-Rayを未使用
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]:
←■そのままEnterでCloudWatchを無効
Project name [sam-app]: ←■そのままEnterでデフォルトの名前「sam-app」になる
Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.9
Architectures: x86_64
Dependency Manager: pip
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-app ディレクトリが作成されます。
Hello WorldのサンプルはPythonですね。
ビルド
ビルドは以下です。
$ cd sam-app
$ sam build
Pythonがインストールされてない場合はエラーになります。
Pythonをインストールするか以下の–use-containerオプションでdockerコンテナでビルドしてもらえるようにします。
$ sam build --use-container
これやるとAWSのECRから必要なDockerイメージを取得してくれます。
デプロイ
デプロイは以下です。
$ sam deploy --guided
初回は–guidedオプションを付けて、2回目以降はなしでいいらしいです。
デプロイが成功したら最後に以下の表示が出てるので
---------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::999999999999:role/sam-app-HelloWorldFunctionRole-CZbfVGATe2ok
Key HelloWorldApi
Description API Gateway endpoint URL for Prod stage for Hello World function
Value https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:ap-northeast-1:999999999999:function:sam-app-HelloWorldFunction-xxxxxxxxxxxx
---------------------------------------------------------------------------------------------------------------------
URLを叩いて実行してみます。
$ curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
リクエストすると以下のJSONが返ってきます。
{"message":"hello world"}
ローカルで実行
以下でDockerイメージ作成されます。
$ sam local invoke
以下で実行。
$ sam local start-api
Initializing the lambda functions containers.
Local image is up-to-date
Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
Mounting /home/abe/projects/SAMTest/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime
container
Containers Initialization is done.
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while
working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local
commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you
update your AWS SAM template
2023-11-09 12:20:47 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:3000
2023-11-09 12:20:47 Press CTRL+C to quit
$ curl http://127.0.0.1:3000
{"message": "hello world"}
ローカルで実行できてますね。
Lambda単体で使うよりは便利そう。
CloudFormationのテンプレートは今一慣れませんので勉強中です。
コメント
コメントを投稿