owned this note
owned this note
Published
Linked with GitHub
# AWS SAMを始める
# 環境準備
[Installing the AWS SAM CLI on Windows - AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-windows.html)
これに沿ってやる
## Step 1: Create an AWS account
持ってる
## Step 2: Configure IAM permissions and AWS credentials
AWSルートアカウントしか持ってなかったのでAdmin権限のIAMロールを作る
[Creating your first IAM admin user and user group - AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html)
これに沿ってやる。特に難しいことはなかった。
最後に出る`数字.signin.aws.amazon.com`のリンクを開くとログアウトされるのでその前にパスワードマネージャーに登録しておくこと。
追加で、作成したIAMロールにログインしてMFAを追加した。
## Step 3: Install Docker (optional)
入ってる
## Step 4: Install the AWS SAM CLI
scoopにありそうだけど見つからなかったので普通にインストーラで入れた
```powershell
PS C:\Users\Eai> sam --version
SAM CLI, version 1.32.0
```
gitは入ってる
# チュートリアル
[Tutorial: Deploying a Hello World application - AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html)
これに沿ってやる
## Step 1: Download a sample AWS SAM application
ディレクトリ掘る
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191> mkdir aws-sam-hello-world
PS C:\Users\Eai\ghq\github.com\eai04191> cd .\aws-sam-hello-world\
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> git init
```
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> 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)
Which runtime would you like to use?
1 - nodejs14.x
2 - python3.9
3 - ruby2.7
4 - go1.x
5 - java11
6 - dotnetcore3.1
7 - nodejs12.x
8 - nodejs10.x
9 - python3.8
10 - python3.7
11 - python3.6
12 - python2.7
13 - ruby2.5
16 - dotnetcore2.1
Runtime: 1
Project name [sam-app]: sam-hello-world
Cloning from https://github.com/aws/aws-sam-cli-app-templates
AWS quick start application templates:
1 - Hello World Example
2 - Step Functions Sample App (Stock Trader)
3 - Quick Start: From Scratch
4 - Quick Start: Scheduled Events
5 - Quick Start: S3
6 - Quick Start: SNS
7 - Quick Start: SQS
8 - Quick Start: Web Backend
Template selection: 1
-----------------------
Generating application:
-----------------------
Name: sam-hello-world
Runtime: nodejs14.x
Dependency Manager: npm
Application Template: hello-world
Output Directory: .
Next steps can be found in the README file at ./sam-hello-world/README.md
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> ls
ディレクトリ: C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2021/09/26 18:02 sam-hello-world
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> mv .\sam-hello-world\* ./
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> ls
ディレクトリ: C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2021/09/26 18:02 events
d----- 2021/09/26 18:02 hello-world
d----- 2021/09/26 18:03 sam-hello-world
-a---- 2021/09/26 18:02 2139 .gitignore
-a---- 2021/09/26 18:02 8346 README.md
-a---- 2021/09/26 18:02 1680 template.yaml
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> rm .\sam-hello-world\
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> ls
ディレクトリ: C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2021/09/26 18:02 events
d----- 2021/09/26 18:02 hello-world
-a---- 2021/09/26 18:02 2139 .gitignore
-a---- 2021/09/26 18:02 8346 README.md
-a---- 2021/09/26 18:02 1680 template.yaml
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world>
```
どうでもいいけどこういうinit系掘ってから始めてるから、そこから掘られると動かす必要があってめんどくさい
テンプレートがたくさんあって便利そう
実際のコードはhello-world/に入っているみたい
![](https://i.imgur.com/yvqs0bD.png)
## Step 2: Build your application
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> sam build
Building codeuri: C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world\hello-world runtime: nodejs14.x metadata: {} functions: ['HelloWorldFunction']
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc
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
```
`npm install`とかしてるみたいだけど、ビルドコマンドとかはどこで指定してるんだろう
> What AWS SAM is doing:
>
> The AWS SAM CLI comes with abstractions for a number of Lambda runtimes to build your dependencies, and copies the source code into staging folders so that everything is ready to be packaged and deployed. The sam build command builds any dependencies that your application has, and copies your application source code to folders under .aws-sam/build to be zipped and uploaded to Lambda.
ふーん
.aws-sam/にビルドされてた
![](https://i.imgur.com/ecefpRH.png)
なんで.aws-sam/が.gitignoreに入っていないんだ
## Step 3: Deploy your application to the AWS Cloud
<details>
<summary>長い</summary>
```
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> sam deploy --guided
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]: sam-hello-world
AWS Region [us-east-1]:
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]:
#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]:
HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: Y
Save arguments to configuration file [Y/n]:
SAM configuration file [samconfig.toml]:
SAM configuration environment [default]:
Looking for resources needed for deployment:
Traceback (most recent call last):
File "runpy.py", line 194, in _run_module_as_main
File "runpy.py", line 87, in _run_code
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\__main__.py", line 12, in <module>
cli(prog_name="sam")
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\cli_validation\image_repository_validation.py", line 85, in wrapped
return func(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\decorators.py", line 73, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\telemetry\metric.py", line 153, in wrapped
raise exception # pylint: disable=raising-bad-type
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\telemetry\metric.py", line 122, in wrapped
return_value = func(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\utils\version_checker.py", line 42, in wrapped
actual_result = func(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\cli\main.py", line 90, in wrapper
return func(*args, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\commands\deploy\command.py", line 216, in cli
do_cli(
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\commands\deploy\command.py", line 303, in do_cli
guided_context.run()
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\commands\deploy\guided_context.py", line 547, in run
self.guided_prompts(_parameter_override_keys)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\commands\deploy\guided_context.py", line 175, in guided_prompts
s3_bucket = manage_stack(profile=self.profile, region=region)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\bootstrap\bootstrap.py", line 22, in manage_stack
outputs: StackOutput = manage_cloudformation_stack(
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\utils\managed_cloudformation_stack.py", line 86, in manage_stack
return _create_or_get_stack(cloudformation_client, stack_name, template_body, parameter_overrides)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\samcli\lib\utils\managed_cloudformation_stack.py", line 97, in _create_or_get_stack
ds_resp = cloudformation_client.describe_stacks(StackName=stack_name)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\client.py", line 386, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\client.py", line 691, in _make_api_call
http, parsed_response = self._make_request(
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\client.py", line 711, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\endpoint.py", line 132, in _send_request
request = self.create_request(request_dict, operation_model)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\endpoint.py", line 115, in create_request
self._event_emitter.emit(event_name, request=request,
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\hooks.py", line 357, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\hooks.py", line 211, in _emit
response = handler(**kwargs)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\signers.py", line 90, in handler
return self.sign(operation_name, request)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\signers.py", line 162, in sign
auth.add_auth(request)
File "C:\Program Files\Amazon\AWSSAMCLI\runtime\lib\site-packages\botocore\auth.py", line 373, in add_auth
raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world>
```
</details>
たぶんcliでawsにログインしてないことに文句を言われている
:::warning
なんでチュートリアルどおりにやったのに文句言われないといけないんだ
:::
> **Amazon SAM CLI error: "Failed to create managed resources: Unable to locate credentials"
When executing sam deploy, you see the following error:**
>
>
> Error: Failed to create managed resources: Unable to locate credentials
>
> This means that you have not set up Amazon credentials to enable the Amazon SAM CLI to make Amazon service calls. To fix this, you must set up Amazon credentials. For more information, see [Setting up Amazon credentials](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-set-up-credentials.html#serverless-getting-started-set-up-credentials-no-cli).
はい
[Setting up Amazon credentials - Amazon Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-set-up-credentials.html#serverless-getting-started-set-up-credentials-no-cli)
AWS CLIは入れてないのでcrendiatialファイルを直接書く
```powershell
> code %UserProfile%/.aws/credentials
```
```ini
[default]
aws_access_key_id = your_access_key_id
aws_secret_access_key = your_secret_access_key
```
値はIAMのダッシュボードからアクセスキーの作成をして得られたもの
とりあえずAdminのIAMで作った
再挑戦
<details>
<summary>長い</summary>
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> sam deploy --guided
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]: sam-hello-world
AWS Region [us-east-1]:
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]:
#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]:
HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: Y
Save arguments to configuration file [Y/n]:
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-1k5sjswibn3ib
A different default S3 bucket can be set in samconfig.toml
Saved arguments to config file
Running 'sam deploy' for future deployments will use the parameters saved above.
The above parameters can be changed by modifying samconfig.toml
Learn more about samconfig.toml syntax at
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
Uploading to sam-hello-world/0bcdce6f6ac7b2822fab2c68d0ef4cde 128407 / 128407 (100.00%)
Deploying with following values
===============================
Stack name : sam-hello-world
Region : us-east-1
Confirm changeset : False
Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-1k5sjswibn3ib
Capabilities : ["CAPABILITY_IAM"]
Parameter overrides : {}
Signing Profiles : {}
Initiating deployment
=====================
Uploading to sam-hello-world/bb618dd15ee7f7350331f5bd0c7411ea.template 1154 / 1154 (100.00%)
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:us-east-1:282467325028:changeSet/samcli-deploy1632649367/b7bc47e9-4bb2-4340-b8f7-c94aa2879a42
2021-09-26 18:43:01 - 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_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi Resource creation Initiated
CREATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi -
CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d -
CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d Resource creation Initiated
CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd Resource creation Initiated
CREATE_IN_PROGRESS 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::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd -
CREATE_COMPLETE AWS::CloudFormation::Stack sam-hello-world -
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::282467325028:role/sam-hello-world-HelloWorldFunctionRole-A5E6R3K4M416
Key HelloWorldApi
Description API Gateway endpoint URL for Prod stage for Hello World function
Value https://rj5ze1h865.execute-api.us-east-1.amazonaws.com/Prod/hello/
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:us-east-1:282467325028:function:sam-hello-world-HelloWorldFunction-BI6atU6WOdUi
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Successfully created/updated stack - sam-hello-world in us-east-1
```
</details>
上手く行ったみたい
![](https://i.imgur.com/FKHd1d2.png)
できてんねえ!
## Step 4: (Optional) Test your application locally
ローカルで動いたら楽しそう
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> sam local start-api
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. You only need to restart SAM CLI if you update your AWS SAM template
2021-09-26 18:50:15 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
```
![](https://i.imgur.com/ZhEfe9F.png)
動いたけどレスポンスがめっちゃ遅い上、Docker Desktopが[wslからやれ💢](https://docs.docker.com/desktop/windows/wsl/#develop-with-docker-and-wsl-2)って怒ってきた。要検討
### Invoke your Lambda function directly
```powershell
PS C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world> sam local invoke "HelloWorldFunction" -e events/event.json
Invoking app.lambdaHandler (nodejs14.x)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-nodejs14.x:rapid-1.32.0.
Mounting C:\Users\Eai\ghq\github.com\eai04191\aws-sam-hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: ef698e5c-6741-464e-b9b8-9858f4fc7706 Version: $LATEST
END RequestId: ef698e5c-6741-464e-b9b8-9858f4fc7706
REPORT RequestId: ef698e5c-6741-464e-b9b8-9858f4fc7706 Init Duration: 0.09 ms Duration: 90.65 ms Billed Duration: 91 ms Memory Size: 128 MB Max Memory Used: 128 MB
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}
```
APIとかじゃないならこれを使うのかな
> What AWS SAM is doing:
>
> The invoke command directly invokes your Lambda functions, and can pass input event payloads that you provide. With this command, you pass the event payload in the file event.json that the sample application provides.
>
> Your initialized application comes with a default aws-proxy event for API Gateway. A number of values are pre-populated for you. In this case, the HelloWorldFunction doesn't care about the particular values, so a stubbed request is OK. You can specify a number of values to substitute in to the request to simulate what you would expect from an actual request. The following is an example of generating your own input event and comparing the output with the default event.json object:
よくわからん
## 消す
作ったスタックを消す
[CloudFormation](https://console.aws.amazon.com/cloudformation/)からポチポチ消す
![](https://i.imgur.com/R3HgnnU.png)
きれいに消えた