uno
uno

Reputation: 1481

Printing s3 bucket upload object key with lambda with Ruby?

The following is a test example supplied by aws lambda for s3 events:

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

I am specifically wondering, how would i print the object: key:?

Specifically"test/key" ?

I have tried this and a few other ways to no success:

require 'json'
require 'aws-sdk-elastictranscoder'
require "aws-sdk-s3"

def lambda_handler(event:, context:)
    src_bkt = "example-bucket"
    src_key = event.Records[0].s3.object.key

    s3.getObject({
        Bucket: src_bkt,
        Key: src_key
    })
    # TODO implement
    { statusCode: 200, body: JSON.generate(src_key) }
end

The response i get with this is a failed response with the following:

Response:
{
  "errorMessage": "undefined method `Records' for #<Hash:0x0000561d9afa6618>",
  "errorType": "Function<NoMethodError>",
  "stackTrace": [
    "/var/task/lambda_function.rb:7:in `lambda_handler'"
  ]
}

Update:

I am able to print the entire Record with:

def lambda_handler(event:, context:)
    body = JSON.generate(event)
    parse = JSON.parse(body)

    puts(parse["Records"])
end

But one i add to the puts/print something like:

puts(parse["Records"]["object"]["key"])

I get errors such as:

"errorMessage": "no implicit conversion of String into Integer",

Upvotes: 0

Views: 564

Answers (1)

SalmonKiller
SalmonKiller

Reputation: 2203

What if you do the following:

record = event["Records"][0]
key = record.dig *%w(s3 object key)

The reason you are confused, I think, is because the event object is a hash with a key Records that contains an array of all of the event records. So instead of converting to JSON, you could pull the record out instead (first line) and then access the key with the dig method of the Hash (I find it really convenient when traversing AWS event record hashes).

Upvotes: 1

Related Questions