LoginSignup
0
1

More than 1 year has passed since last update.

AWS SAMでGo+API Gateway+Lambda+DynamoDBのサーバレスAPI構築をIaC化した

Posted at

はじめに

前回Goで作成したAPIの環境構築をSAMでIaC化しました。

環境

MacBook Air M1
開発言語 Go

手順

AWS CLIとSAM CLIをインストールします。

brew install awscli
brew tap aws/tap
brew install aws-sam-cli

AWSコンソールのIAMからアクセスキーを作成して、クレデンシャルを設定します。

aws configure

前回のソースディレクトリにSAMのtemplate.yamlを追加します。

ソースコード

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: go-serverless-app-4

Resources:
  Function:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: PostAmazonURLFunction
      Handler: PostAmazonURLFunction
      Role: !GetAtt FunctionRole.Arn
      Runtime: go1.x
      CodeUri: .
      Timeout: 60
      Architectures:
        - x86_64
      Events:
        CatchAll:
          Type: Api
          Properties:
            Path: /post
            Method: POST
  Table:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: Number
      TableName: table
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
  FunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - lambda.amazonaws.com
      Policies:
        - PolicyName: DynamoDBPutItemPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - dynamodb:PutItem
                Resource: !GetAtt Table.Arn

go1.19へアップデートしていたりtemplate.yamlを含む微修正版。

ソースコードの準備ができたら、SAMのビルドコマンドを実行します。

sam build

ビルドが完了したら、デプロイコマンドを--guidedオプションをつけて実行します。

sam deploy --guided

指示に従って、必要な情報を入力します。

デプロイが完了したら、APIのエンドポイントへリクエストを送って問題ないか確認します。
私はAPI Gatewayからテストを選択してbodyに以下を入力して実行しました。

{
    "url": "http://www.amazon.co.jp"
}

ステータスコード:200, "SUCCESS"が帰ってきたら成功です。

テストが完了したら、CloudFromationのスタックの削除をして、
リソースを削除することを忘れないようにしましょう!

最後に

前回の記事で手作業でやった手順がほぼ自動化されたので環境構築が大分楽になったという感想です。
一からテンプレートを作成するのが初めてだったので、所々ハマって時間が掛かってしまったんですが勉強にはなりました。

次回は、登録したURLを取得したり、登録する際のアルゴリズムを修正するところまでいけたらと思います。

最後まで読んでいただきありがとうございました!:bow:

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1