🦔

AWS SAMでサーバーレス構築

2024/05/23に公開

全体の流れ

EventBridgeスケジュール実行

Lambda関数が実行

(samデプロイ時にパラメータストアから取得して環境変数を設定)

コマンド

雛形作成

$ sam init

作成されるディレクトリやファイル
├── README.md
├── events
│   └── event.json
├── sam-example
│   ├── app.ts
│   ├── babel.config.js
│   ├── coverage
│   ├── jest.config.ts
│   ├── node_modules
│   ├── package-lock.json
│   ├── package.json
│   ├── tests
│   └── tsconfig.json
├── samconfig.toml
├── template.yaml

初回構築

sam deploy --guided
ここで諸々構築されます

デプロイ

$ sam build
$ sam deploy

ローカル実行

$ sam build
$ sam local invoke

ローカルで環境変数を設定したい場合

$ sam local invoke --env-vars env.json

使い方

vars.json

{
  "Parameters": {
    "SECRET_KEY": "****************"
  }
}

環境変数の利用

process.env.SECRET_KEY

削除

$ sam delete --stack-name sam-app
まるっと削除されます

template.yml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

Globals:
  Function:
    Timeout: 30
    Environment:
      Variables:
        SECRET_KEY: !Sub '{{resolve:ssm:SecretKey:1}}'

Resources:
  SampleSamAppFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: sample-sam-app/
      Handler: app.lambdaHandler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: "es2020"
        Sourcemap: true
        EntryPoints: 
        - app.ts
  SampleSamAppRule:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: "cron(0 9 * * ? *)"
      Targets:
        - Arn: !GetAtt SampleSamAppFunction.Arn
          Id: "TargetFunction"
  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt SampleSamAppFunction.Arn
      Principal: "events.amazonaws.com"
      SourceArn: !GetAtt SampleSamAppRule.Arn
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: [ lambda.amazonaws.com ]
            Action: [ 'sts:AssumeRole' ]
      Policies:
        - PolicyName: 'LambdaAccessSSM'
          PolicyDocument:
            Version: '2012-10-17'template.yaml
            Statement:
              - Effect: Allow
                Action: [ 'ssm:GetParameter' ]
                Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/*'

Outputs:
  SampleSamAppFunction:
    Description: "SampleSamAppFunction Lambda Function ARN"
    Value: !GetAtt SampleSamAppFunction.Arn
  SampleSamAppFunctionIamRole:
    Description: "Implicit IAM Role created for SampleSamAppFunction function"
    Value: !GetAtt SampleSamAppFunctionRole.Arn

触ったきっかけ

  • Lambdaをローカル実行できて、デプロイも簡単にできるもの
  • Serverless Framework, AWS CDKは触ったことあったのでやってみた

version

$ sam --version
SAM CLI, version 1.116.0

Discussion