Mark Needham

Thoughts on Software Development

AWS Lambda: Programatically create a Python ‘Hello World’ function

with 2 comments

I’ve been playing around with AWS Lambda over the last couple of weeks and I wanted to automate the creation of these functions and all their surrounding config.

Let’s say we have the following Hello World function:

def lambda_handler(event, context):
    print("Hello world")

To upload it to AWS we need to put it inside a zip file so let’s do that:

$ zip
$ unzip -l 
  Length     Date   Time    Name
 --------    ----   ----    ----
       61  04-02-17 22:04
 --------                   -------
       61                   1 file

Now we’re ready to write a script to create our AWS lambda function.

import boto3
lambda_client = boto3.client('lambda')
fn_name = "HelloWorld"
fn_role = 'arn:aws:iam::[your-aws-id]:role/lambda_basic_execution'
    Code={'ZipFile': open("{0}.zip".format(fn_name), 'rb').read(), },

[your-aws-id] needs to be replaced with the identifier of our AWS account. We can find that out be running the following command against the AWS CLI:

$ aws ec2 describe-security-groups --query 'SecurityGroups[0].OwnerId' --output text

Now we can create our function:

$ python

2017 04 02 23 07 38

And if we test the function we’ll get the expected output:

2017 04 02 23 02 59

Be Sociable, Share!

Written by Mark Needham

April 2nd, 2017 at 10:11 pm

Posted in Software Development

Tagged with ,

  • OpenWatch

    Alternately, you could use a framework like Zappa to take care of all of this for you:

  • @disqus_kttDIhaXQ8:disqus cool thanks, hadn’t heard of that before. Will give it a try.