Execution Error - Handler 'lambda_handler' missing on module 'lambda_function'"

Viewed 364

Below is the code and the error that I'm getting while testing in Lambda. I'm a newbie in python & serverless. Please help. This is created for uploading the findings from the security hub to S3 for POC.

import boto3
import json
from botocore.exceptions import ClientError
import time
timestr = time.strftime("%Y%m%d-%H%M%S")

storedata = {}
client = boto3.client('securityhub')
_filter = Filters={
    'GeneratorId': [
        {
            'Value': 'arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark',
            'Comparison': 'PREFIX'
        }
    ],
}

response = client.get_findings(Filters=_filter)
storedata = json.dumps(response)
print(storedata)

def aws_session(region_name='eu-west-1'):
  return boto3.session.Session()

def upload_data_to_bucket(data, bucket_name, s3_key):
  session = aws_session()
  s3_resource = session.resource('s3')
  obj = s3_resource.Object(bucket_name, s3_key)
  obj.put(ACL='private', Body=data)

  s3_url = f"https://{bucket_name}.s3.amazonaws.com/{s3_key}"
  return s3_url

s3_url = upload_data_to_bucket(storedata, 'sdhkdhiufhasp', 'securityhub_findings.json')
print(s3_url)
1 Answers

When we use Lambda we need to write our code inside the lambda_handler method
"def lambda_handler(event, context):" .

As you mentioned you are using lambda to run this code then probably the below code should work for you.

    import boto3
    import json
    from botocore.exceptions import ClientError
    import time
    import glob 
   
    client = boto3.client('securityhub')
    s3 = boto3.resource('s3')
     
     
     storedata = {}
     _filter = Filters={
        'GeneratorId': [
            {
                'Value': 'arn:aws:securityhub:::ruleset/cis-aws-foundations- 
       benchmark',
                'Comparison': 'PREFIX'
            }
        ],
      }

   def lambda_handler(event, context):
    response = client.get_findings(Filters=_filter)
    storedata = json.dumps(response)
    print(storedata)

    save_file = open("/tmp/securityhub_findings.json", "w")
    save_file.write(storeddata)
    save_file.close()
 
    for name in glob.glob(/tmp/*):  
      s3.meta.client.upload_file(name, "you_bucket_name", name)
 
Related