Bootstrap FreeKB - Amazon Web Services (AWS) - Creating your own Lambda Layer Python module
Amazon Web Services (AWS) - Creating your own Lambda Layer Python module


Here is an example Python module that will publish a message to an Amazon Web Services (AWS) Simple Notification Service (SNS) Topic. This is the minimal boilerplate code without any error handling.

#!/usr/bin/python3
import boto3

client = boto3.client('sns')
client.publish(
  TopicArn=arn,
  Subject=subject,
  Message=message
)

 

Here is a more practical example, with try/except/else error handling. Let say you wan to make this into a Lambda Layer, so that your Lambda Functions can import the publish_message_to_sns_topic function.

#!/usr/bin/python3
import boto3
def publish_message_to_sns_topic(arn, subject, message):

    try:
        client = boto3.client('sns')
    except Exception as exception:
        return { "result": "failed"}

    try:
        client.publish(
            TopicArn=arn,
            Subject=subject,
            Message=message
        )
    except Exception as exception:
        return { "result": "failed"}
    else:
        return { "result": "success"}

 

Move into the /tmp directory and create a directory named "python" and create a file named publish_message_to_sns_topic.py that contains the above markup. This is needed so that when the zip file is created, the base directory in the zip archive will be python and all of the files and directories that were extracted will be below the python directory. Refer to Packaging your layer content - AWS Lambda (amazon.com) for more details on why this is required.

/tmp/python/publish_message_to_sns_topic.py

 

Use the zip command to create a zip file that contains the contents of the python directory.

zip --recurse-path publish_message_to_sns_topic.zip python/

 

Now you can use the aws lambda publish-layer-version command to create a Lambda Layer using the .zip file.

aws lambda publish-layer-version --layer-name publish_message_to_sns_topic --zip-file fileb://publish_message_to_sns_topic.zip

 

Or, in the AWS console, create a Lambda Layer using the zip file, something like this. Make note of the Amazon Resource Number (ARN) of the layer.

 

And here is an example of how you could import and call the function in the Lambda Layer in one of your Lambda Functions.

from publish_message_to_sns_topic import publish_message_to_sns_topic 

def lambda_handler(event, context):

  publish_message_to_sns_topic("arn:aws:sns:us-east-1:123456789012:my-topic", "message subject", "message body")

  return {
      'statusCode': 200,
      'body': json.dumps({
          "result": "success",
          "message": f"successfully published message to SNS topic"
      })
  }

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 05c598 in the box below so that we can be sure you are a human.