AWS SAM 自習1日目
AWS サーバーレスアプリケーションモデル(SAM、Serverless Application Model) を利用すると、API Gateway や Lambdaの設定が定義ファイルにて可能になるということなので、チュートリアルをやってみる。
AWS SAM CLI のインストール
SAM CLIをインストールする
brew install aws-sam-cli
または、
brew upgrade aws-sam-cli
チュートリアル
下記のチュートリアルをやってみる。
サンプルアプリのダウンロード
$ 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
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1
What package type would you like to use?
1 - Zip (artifact is a zip uploaded to S3)
2 - Image (artifact is an image uploaded to an ECR image repository)
Package type: 1
Which runtime would you like to use?
1 - nodejs14.x
2 - python3.8
3 - ruby2.7
4 - go1.x
5 - java11
6 - dotnetcore3.1
7 - nodejs12.x
8 - nodejs10.x
9 - python3.7
10 - python3.6
11 - python2.7
12 - ruby2.5
13 - java8.al2
14 - java8
15 - dotnetcore2.1
Runtime: 2
Project name [sam-app]:
Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates
AWS quick start application templates:
1 - Hello World Example
2 - EventBridge Hello World
3 - EventBridge App from scratch (100+ Event Schemas)
4 - Step Functions Sample App (Stock Trader)
5 - Elastic File System Sample App
Template selection: 1
-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.8
Dependency Manager: pip
Application Template: hello-world
Output Directory: .
Next steps can be found in the README file at ./sam-app/README.md
$ ls -la
total 0
drwxr-xr-x 3 kazoo staff 96 Feb 20 14:02 .
drwxr-xr-x 6 kazoo staff 192 Feb 20 13:59 ..
drwxr-xr-x 9 kazoo staff 288 Feb 20 14:02 sam-app
$ tree
.
└── sam-app
├── README.md
├── __init__.py
├── events
│ └── event.json
├── hello_world
│ ├── __init__.py
│ ├── app.py
│ └── requirements.txt
├── template.yaml
└── tests
├── __init__.py
├── integration
│ ├── __init__.py
│ └── test_api_gateway.py
├── requirements.txt
└── unit
├── __init__.py
└── test_handler.py
$ sam --version
SAM CLI, version 1.18.2
sam build
sam build を実行すると、Pythonのバージョンでエラーになった。
$ sam build
Building codeuri: hello_world/ runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']
Build Failed
Error: PythonPipBuilder:Validation - Binary validation failed for python, searched for python in following locations : ['/Users/kazoo/anaconda/bin/python', '/usr/bin/python'] which did not satisfy constraints for runtime: python3.8. Do you have python for runtime: python3.8 on your PATH?
$ python --version
Python 3.6.0 :: Anaconda custom (x86_64)
以前Pythonはanacondaでインストールしたようなので、anacondaをupdateする。
$ conda update --prefix /Users/kazoo/anaconda anaconda
※--prefix にはanacondaのパスを指定。
Pythonのバージョンは3.6.0→3.6.2にしか上がらずsam buildはエラーになるので、一旦Anacondaを公式にしたがって削除し、その上でPython3.8をインストールすることにする。
Anaconda アンインストール方法
which conda
/Users/user/anaconda/bin/conda
conda install anaconda-clean
anaconda-clean --yes
sudo rm -rf ~/anaconda
.bash_profileのanacondaパスを削除します。
Pipenvのインストール
pipのパッケージマネージャーとしてPipenvをインストールする。
Pyenvのインストール
PythonのバージョンマネージャーPyenvをインストールする。
Homebrewでpyenvをインストール
brew install pyenv
.pyenvをGitからクローン
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
.bash_profileに設定を追加
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
source .bash_profile
pyenvでPythonのコンパイルに必要なライブラリをインストール
xcode-select --install
brew install openssl readline sqlite3 xz zlib
Pythonのインストール
pyenvでPython3.9.2をインストールする。
pyenv install 3.9.2
$ python -V
Python 2.7.16
$ pyenv --help
Usage: pyenv <command> [<args>]
Some useful pyenv commands are:
--version Display the version of pyenv
commands List all available pyenv commands
exec Run an executable with the selected Python version
global Set or show the global Python version(s)
help Display help for a command
hooks List hook scripts for a given pyenv command
init Configure the shell environment for pyenv
install Install a Python version using python-build
local Set or show the local application-specific Python version(s)
prefix Display prefix for a Python version
rehash Rehash pyenv shims (run this after installing executables)
root Display the root directory where versions and shims are kept
shell Set or show the shell-specific Python version
shims List existing pyenv shims
uninstall Uninstall a specific Python version
version Show the current Python version(s) and its origin
version-file Detect the file that sets the current pyenv version
version-name Show the current Python version
version-origin Explain how the current Python version is set
versions List all Python versions available to pyenv
whence List all Python versions that contain the given executable
which Display the full path to an executable
See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme
$ pyenv rehash
$ pyenv versions
* system (set by /Users/user/.pyenv/version)
3.9.2
$ pyenv global 3.9.2
$ pyenv version
3.9.2 (set by /Users/user/.pyenv/version)
$ python -V
Python 3.9.2
sam build エラー
sam buildに必要なPythonのバージョンは3.8のようでエラーになった。
$ sam build
Building codeuri: hello_world/ runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']
Build Failed
Error: PythonPipBuilder:Validation - Binary validation failed for python,
searched for python in following locations : ['/Users/user/.pyenv/shims/python',
'/usr/bin/python'] which did not satisfy constraints for runtime: python3.8. Do you have python for runtime: python3.8 on your PATH?
Python3.8.8をインストール。
$ pyenv install 3.8.8
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.8.8.tar.xz...
-> https://www.python.org/ftp/python/3.8.8/Python-3.8.8.tar.xz
Installing Python-3.8.8...
python-build: use readline from homebrew
python-build: use zlib from xcode sdk
Installed Python-3.8.8 to /Users/user/.pyenv/versions/3.8.8
$ pyenv rehash
$ pyenv versions
system
3.8.8
* 3.9.2 (set by /Users/user/.pyenv/version)
$ pyenv global 3.8.8
$ pyenv versions
system
* 3.8.8 (set by /Users/user/.pyenv/version)
3.9.2
ビルド
再度 sam buildを実行
$ sam build
Building codeuri: hello_world/ runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
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
ビルド成功。
デプロイ
アプリをAWSにデプロイする。
$ sam deploy --guided
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
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]:
#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: Not found.
Creating the required resources...
Successfully created!
・・・
API 接続テスト
curlでAPIにリクエストしてテストする。
curl https://<restapiid>.execute-api.us-east-1.amazonaws.com/Prod/hello/
{"message": "hello world"}
成功
ローカル環境でテスト
sam local コマンドを実行してローカルにてテスト。
$ 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-02-21 22:34:59 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
・・・
ブラウザで http://127.0.0.1:3000/hello に接続する。
OK。