maxmcc
maxmcc

Reputation: 69

How to get s3 bucket name and key of a file, from an event in lambda

We have a trigger set on a lambda function and would like to grab the newest file from an S3 bucket when it is dropped into it. The filename will change. We want to grab the file object from the event but cannot figure out how.

Right now, we have the direct filename written as a variable in the lambda function and are testing it locally. It seems to work but we want to make our lambda generic and grab the file using the event param passed in. Basically, we need to swap out these two lines and make them generic.

const bucket = 'bucket-12345';
const key = 'testXML.xml';

Thank you for any assistance.

Upvotes: 4

Views: 22494

Answers (2)

skellertor
skellertor

Reputation: 1105

Here is what the event looks like. The documentations can be found here as @MarkB mentions in the comments.

You will find what you need at event.Records[index].s3.object.key. Depending on your bucket structure, the key might look like a path. In that case you will just need to parse out the end of the key which will contains the file name.

{
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "eTag": "0123456789abcdef0123456789abcdef",
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "HappyFace.jpg",
          "size": 1024
        },
        "bucket": {
          "arn": bucketarn,
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
}

Upvotes: 1

madhead
madhead

Reputation: 33412

Take a look at this example:

exports.handler = function(event, context, callback) {
    var bucket = event.Records[0].s3.bucket.name;
    var key = event.Records[0].s3.object.key;
    …
}

Upvotes: 4

Related Questions