AWS SAMを使ってみた

  • #開発
  • #AWS

こんにちは。CURUCURU の長尾です。

今回は AWS SAM に関して書いていきます。

先日、lambda にていい感じのバッチを作りたい要件があり今まではローカルで書いたファイルを zip で送信していたんですが、SAM というものがあるのを知って使ってみたらとても便利だったのでここで紹介します。

何ができるの?

SAM では AWS サーバレス 環境の Cloud Formation のテンプレートを簡単に作成できます。

lambda の環境を今まで手動で整えていた人が SAM を使うと、とても有意義なものだと感じます。

Cloud Formation

AWS におけるインフラ構築をコード化するためのサービス。いわゆる IaC です。

インストール

$ wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip

$ unzip aws-sam-cli-linux-x86_64.zip -d sam-installation

$ sudo ./sam-installation/install

$ sam --version
SAM CLI, version 1.46.0

使ってみる

今回は APIGateway を使わずに lambda 単体でバッチのようなものを Go で作ります。

sam initコマンドを使うだけで対話式でテンプレートを作成してくれます。

$ 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

# テンプレートの種類の選択。今回はHelloWorldしましょう。
Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Infrastructure event management
        8 - Machine Learning
Template: 1

# pythonとzipでのアップロード使った構成が一番人気だからそれを使う?と聞いてきますがここはNoで。
Use the most popular runtime and package type? (Python and zip) [y/N]: N

# ランタイムの選択。今回はGoで。
Which runtime would you like to use?
        1 - dotnet6
        2 - dotnet5.0
        3 - dotnetcore3.1
        4 - go1.x
        5 - java11
        6 - java8.al2
        7 - java8
        8 - nodejs14.x
        9 - nodejs12.x
        10 - python3.9
        11 - python3.8
        12 - python3.7
        13 - python3.6
        14 - ruby2.7
Runtime: 4

# lambdaへのデプロイを何で行うのか。zipかDocker Imageか選択できます。今回はImageで。
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 mod.
We will proceed copying the template using mod.

# プロジェクト名を聞かれるので適当に。
Project name [sam-app]: curucuru-batch

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: curucuru-batch
    Base Image: amazon/go1.x-base
    Architectures: x86_64
    Dependency Manager: mod
    Output Directory: .
    Next steps can be found in the README file at ./curucuru-batch/README.md


    Commands you can use next
    =========================
    [*] Create pipeline: cd curucuru-batch && sam pipeline init --bootstrap
    [*] Test Function in the Cloud: sam sync --stack-name {stack-name} --watch

# これで以下のようなテンプレートが自動生成されます。
$ tree
.
└── curucuru-batch
    ├── README.md
    ├── hello-world
    │   ├── Dockerfile
    │   ├── go.mod
    │   ├── go.sum
    │   ├── main.go
    │   └── main_test.go
    └── template.yaml

2 directories, 7 files

$ cd curucuru-batch

# 手元で試す前にまずはビルドします。--use-containerをつけておくとLambdaと同じような実行環境下でテストできます。
$ sam build --use-container

# 手元でテスト。テンプレートの中身は実行環境のIPを表示してくれるだけのものです。bodyの中にIPが表示されれば正常です。
$ sam local invoke
Invoking Container created from helloworldfunction:go1.x-v1
Building image.................
Skip pulling image and use local one: helloworldfunction:rapid-1.46.0-x86_64.

START RequestId: 329bb472-eed3-4e04-a8bf-2b4916f2610b Version: $LATEST
{"statusCode":200,"headers":null,"multiValueHeaders":null,"body":"Hello, xxx.xxx.xxx.xxx\n"}END RequestId: 329bb472-eed3-4e04-a8bf-2b4916f2610b
REPORT RequestId: 329bb472-eed3-4e04-a8bf-2b4916f2610b  Init Duration: 0.28 ms  Duration: 848.16 ms     Billed Duration: 849 ms       Memory Size: 128 MB     Max Memory Used: 128 MB

# ではこれをデプロイ --guidedをつけると対話形式でデプロイできます。
$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        =========================================
        # 今回のスタックの名前を入力。これはCloud Formationのこと。
        Stack Name [sam-app]: curucuru-batch
        # Regionの設定。
        AWS Region [ap-northeast-1]:
        # デプロイ前に差分を表示するかどうかでここはYes
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: y
        # SAMが実行に必要なIAMroleを作るのを許可するかどうか。ここはYes
        #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]:
        # Lambda APIが認証機構をもっていないことを許可するかどうか。ここはYes
        HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
        # デプロイの設定を保存しておくかどうか。ここはYes
        Save arguments to configuration file [Y/n]: Y
        # 設定ファイルの名前は適当に。今回はそのまま。
        SAM configuration file [samconfig.toml]:
        SAM configuration environment [default]:

        Looking for resources needed for deployment:
         Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1b2hqy96hafr0
         A different default S3 bucket can be set in samconfig.toml
         Image repositories: Not found.
         # ECRにイメージのデプロイをするかどうか。Yes。
         #Managed repositories will be deleted when their functions are removed from the template and deployed
         Create managed ECR repositories for all functions? [Y/n]: Y

    --- 色々流れるので省略

    # デプロイするかどうかを聞かれるのでYes
    Previewing CloudFormation changeset before deployment
    ======================================================
    Deploy this changeset? [y/N]: y

    --- 色々流れて
    Key                 HelloWorldAPI
    Description         API Gateway endpoint URL for Prod environment for First Function
    Value               https://xxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/

    Successfully created/updated stack - curucuru-batch in ap-northeast-1
    # これが表示されたらデプロイ完了

# initしたままデプロイするとAPIのURLがアウトプット表示されますのでcurlしてみると以下のようにIPが返ってきたら成功
$ curl https://xxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
Hello, xxx.xxx.xxx.xxx

まとめ

今回は SAM をデフォルトのままデプロイしてみました。 本当に簡単に Lambda 環境を構築できるのはとてもいいですね。Lambda 使って何かしたいときにはぜひ使ってみてください。

最近よく使うコマンド

最後の締めくくりは Tips で締めます。

$ cat ~/.ssh/id_rsa.pub | pbcopy

mac のターミナルでコピーしたいときの pbcopy。

以上、今回は長尾がお届けしました。