cosmos-1905-14
cosmos-1905-14

Reputation: 1283

KeyError: 's3' in Lambda logs

I'm running a basic Lambda function to get notified it works with my test json, which I got from SNS email, but I get an error with the real action.

Here is the lambda function:

#!/usr/bin/python3.6
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/XXXXXXXXXXXX"
    msg = {
        "channel": "#aws-space",
        "text": event['Records'][0]['s3']['bucket']['name'],
    }
    
    encoded_msg = json.dumps(msg).encode('utf-8')
    resp = http.request('POST',url, body=encoded_msg)
    print({
        "message": event['Records'][0]['s3']['bucket']['name'], 
        "status_code": resp.status, 
        "response": resp.data
    })
    
    

Test JSON:

{
  "Records": [
    {
      "eventVersion": "2.1",
      "eventSource": "aws:s3",
      "awsRegion": "us-east-1",
      "eventTime": "2021-04-04T20:32:38.884Z",
      "eventName": "ObjectRemoved:Delete",
      "userIdentity": {
        "principalId": "AWS:XXXXXXXXXXXXXX"
      },
      "requestParameters": {
        "sourceIPAddress": "XX.XX.XX.XX"
      },
      "responseElements": {
        "x-amz-request-id": "8CXXXXXXXXXXHRQX",
        "x-amz-id-2": "doZ3+gxxxxxxx"
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "Delete-Event",
        "bucket": {
          "name": "bucket-name",
          "ownerIdentity": {
            "principalId": "xxxxxxx"
          },
          "arn": "arn:aws:s3:::bucket-name"
        },
        "object": {
          "key": "deleted-object.png",
          "sequencer": "0060XXXXXXX75X"
        }
      }
    }
  ]
}

I grabbed this python example from AWS doc, https://aws.amazon.com/premiumsupport/knowledge-center/sns-lambda-webhooks-chime-slack-teams/

So it's supposed to work. With test json works fine, but I get no slack notificiation on the real action and when checking lambda logs I see the error below.

's3': KeyError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 9, in lambda_handler
    "text": event['Records'][0]['s3']['bucket']['name'],
KeyError: 's3'

To troubleshoot, I also printed json output in lambda, it seems I'm using the right path and Lambda is able to fetch it as well. I couldnt figure out why the key error occurs.

Any leads will be appreciated, thanks!

Upvotes: 0

Views: 558

Answers (1)

DabvAstur
DabvAstur

Reputation: 49

You are passing NoneType object to lambda_handler function so you are "cleaning" the event and context of Lambda.

Remove this from your lambda function:

if __name__ == "__main__":
    print(lambda_handler(None, None))

And make sure that the handler of lambda call to lambda_handler : enter image description here

Upvotes: 1

Related Questions