1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

S3にオブジェクトをアップロードして引数をlambdaに送りたいとき

Posted at

今まではS3をトリガーにLambdaを発火させていたのですが、これだと追加の変数を設定することができず、どうすればいいか悩んでいたときに、InvokeInputに渡せばいいことを知りました。

参考

go server側

S3にアップロードしたあとに、invokeして変数を渡すようにしました。

main.go
package main

import (
	"encoding/json"
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/lambda"
)

// これはLambda関数の完了で返すための構造体定義
type Response struct {
	Message string `json:"message"`
	Ok      bool   `json:"ok"`
}

// 別のLambdaに渡すための構造体定義
type Event struct {
	Records []Record `json:"Records"`
}

type Record struct {
	S3    S3    `json:"s3"`
	Input Input `json:"input"`
}

type Input struct {
	OriginLocation      string `json:"originLocation"`
	DestinationLocation string `json:"destinationLocation"`
	FrameID             string `json:"frameNumber"`
}

type S3 struct {
	Bucket Bucket `json:"bucket"`
	Object Object `json:"object"`
}

type Bucket struct {
	Name string `json:"name"`
}

type Object struct {
	Key string `json:"key"`
}

func Handler() (Response, error) {
	fmt.Println("handler")
	// 呼び出したLambdaに渡すデータ
	payload := Event{
		[]Record{
			{
				S3{
					Bucket{
						Name: "uploaded-photos",
					},
					Object{
						Key: "xxxxxx.jpg",
					},
				},
				Input{
					OriginLocation:      "HND",
					DestinationLocation: "TPE",
					FrameID:             "frame",
				},
			},
		},
	}
	jsonBytes, _ := json.Marshal(payload)

	// このlambdaはaws/aws-lambda-go/lambdaではなく、
	// aws/aws-sdk-go-aws/service/lambdaなので注意
	svc := lambda.New(session.New(&aws.Config{
		Region: aws.String("ap-northeast-1")}))

	input := &lambda.InvokeInput{
		FunctionName:   aws.String("arn:aws:lambda:ap-northeast-1:xxxxxx:function:CreateThumbnail"),
		Payload:        jsonBytes,
		InvocationType: aws.String("Event"),
	}

	_, _ = svc.Invoke(input)

	return Response{
		Message: "success",
		Ok:      true,
	}, nil
}

func main() {
	fmt.Println("start")
	Handler()
}

lambda側

Lambda側ではrecordの中の引数を受け取るようにしました。

lambda_function.py
def lambda_handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = unquote_plus(record['s3']['object']['key'])

        selectedImageID = record['input']['frameID']
        originLocation = record['input']['originLocation']
        destinationLocation = record['input']['destinationLocation']
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?