在S3桶中放入一个新对象时触发Lambda函数的命令代码

101 阅读1分钟

如果你想在S3桶中放入一个新对象时触发Lambda函数,请使用下面的命令。

设置

// Create lambda function

GOOS=linux CGO_ENABLED=0 go build -ldflags "-s -w" -o lambda/plain/main lambda/plain/main.go

zip lambda.zip lambda/plain/main

aws --profile localstack --endpoint-url http://localhost:4566 lambda create-function \
    --function-name test-lambda \
    --handler lambda/plain/main \
    --runtime go1.x \
    --role test-role \
    --zip-file fileb://lambda.zip

// Create S3 bucket
aws --profile localstack --endpoint-url http://localhost:4566 s3 mb s3://test-bucket

// Configure S3 and Lambda notification
aws --profile localstack --endpoint-url http://localhost:4566 s3api put-bucket-notification-configuration \
    --bucket test-bucket \
    --notification-configuration '{"LambdaFunctionConfigurations":[{"Id":"1","LambdaFunctionArn":"arn:aws:lambda:eu-west-1:000000000000:function:test-lambda","Events":["s3:ObjectCreated:Put"]}]}'

测试

aws --profile localstack --endpoint-url http://localhost:4566 s3 cp test.txt s3://test-bucket

这是你的Lambda事件的样子:

map[
    Records:[
        map[
            awsRegion:eu-west-1
            eventName:ObjectCreated:Put
            eventSource:aws:s3
            eventTime:2022-01-21T13:54:29.483Z
            eventVersion:2.1
            requestParameters:map[
                sourceIPAddress:127.0.0.1
            ]
            responseElements:map[
                x-amz-id-2:efp51TnqcoF8ehtrt9Z/2
                x-amz-request-id:c517
            ]
            s3:map[
                bucket:map[
                    arn:arn:aws:s3:::test-bucket
                    name:test-bucket
                    ownerIdentity:map[
                        principalId:A3NLZZKExample
                    ]
                ]
                configurationId:testConfigRule
                object:map[
                    eTag:"b054ccc597fedf6c"
                    key:test.txt
                    sequencer:0D6DCD90
                    size:10
                    versionId:
                ]
                s3SchemaVersion:1.0
            ]
            userIdentity:map[
                principalId:ARKLGMP
            ]
        ]
    ]
]