404 not found

備忘録です

AWS SAMでs3 eventをトリガーにしたlambdaを実装する

sfender.hatenablog.com の続き

やりたいこと

前回記事で作成したlambdaの親lambdaをs3eventをトリガーにして起動したい。 s3イベントの条件は、pngデータがuploadされたとき。

template.yaml

変更したのはtemplate.yamlのみ。

sam-example-put-objectというバケットを作成して、 同バケットpngファイルが保存されたのをトリガーにHelloWorldFunctionを起動するようにしている。

lambdaの処理は適当。

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  Sample SAM Template for multiple lambda
Globals:
  Function:
    Timeout: 3
    Environment:
      Variables:
        SAMPLACE: "AWS"
Parameters:
  BucketName:
    Type: String
    Default: sam-example-put-object
  FuncParentName:
    Type: String
    Default: HelloWorldFunctionParent
  FuncChildName:
    Type: String
    Default: HelloWorldFunctionChild
  DataSuffix:
    Type: String
    Default: png
Resources:
  DataBucket:
    Type: "AWS::S3::Bucket"
    Properties:
      BucketName: !Sub "${BucketName}"
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      FunctionName: !Sub "${FuncParentName}"
      Environment:
        Variables:
          CHILDLAMBDAARN: !GetAtt HelloWorldFunctionChild.Arn
      Events:
        BucketEvent:
          Type: S3
          Properties:
            Bucket:
              Ref: DataBucket
            Events:
              - "s3:ObjectCreated:*"
            Filter:
              S3Key:
                Rules:
                  - Name: suffix
                    Value: !Sub "${DataSuffix}"
      Policies:
        - CloudWatchPutMetricPolicy: {}
        - LambdaInvokePolicy:
            FunctionName: !Sub "${FuncChildName}"
        - S3CrudPolicy:
            BucketName: !Sub "${BucketName}"
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: python3.8-v1
  HelloWorldFunctionChild:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      FunctionName: !Sub "${FuncChildName}"
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world_child
      DockerTag: python3.6-v1
Outputs:
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionChild:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunctionChild.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn
  HelloWorldFunctionChildIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionChildRole.Arn

tips

  • resouce外でバケット名を作っておく
    • こうしておかないとpolicyのリソース指定とかで循環参照エラーが発生する。
  • 親lambdaにpolicyを設定
    • 子lambdaを叩けるようにpolicyをアタッチ。
    • この時、cloudwatchのput metricsをつけておかないとログが見れない
  • parameterの設定
    • 関数名とかは外だししてみた。