Create AWS Lambda Function Using CLI

I enjoy using the AWS CLI to deploy AWS Services. In this article I will deploy and invoke a Python Lambda Function using the CLI. The Python Handler will be uploaded to an S3 bucket as a zip file.

Step 1: Create Handler for AWS Lambda

Using Visual Studio Code create a file.

import json

def hello(event, context):
    body = {
        "message": "Hello from Python 3.6!",
        "input": event

    response = {
        "statusCode": 200,
        "body": json.dumps(body)

    return response

Add it to a zip file and create and store it in an S3 bucket.

$ zip

$ aws s3 mb s3://my-lambda-repository

$ aws s3 cp s3://my-lambda-repository

Step 2: Generate JSON Skeleton to Create Lambda Function

Generate a JSON skeleton for the create-function command using the AWS CLI and open it in Visual Studio Code.

$ aws lambda create-function --generate-cli-skeleton > create-lambda.json

$ code create-lambda.json

Fill in the JSON with your specific details. This assumes you have an IAM Role with the basic lambda execution role policy. Add the ARN to your JSON file.

    "FunctionName": "HelloPython",
    "Runtime": "python3.6",
    "Role": "{basic lambda execution role arn}",
    "Handler": "handler.hello",
    "Code": {
        "S3Bucket": "my-lambda-repository",
        "S3Key": ""

Step 3: Create and Invoke Lambda Function

Run the commands to create and invoke the new Lambda Function. Store the results in an output.json file.

$ aws lambda create-function --cli-input-json file://create-lambda.json

$ aws lambda invoke --function-name HelloPython output.json

    "StatusCode" : 200

Display the results in the output.json file.

$ cat output.json | python -m json.tool

    "statusCode": 200,
    "body": "{\"message\": \"Hello from Python 3.6!\", \"input\": {}}"

Step 4: Clean Up Resources

It’s a good idea to clean up resources when you no longer need them. Delete the S3 Bucket and Lambda Function.

$ aws s3 rb s3://my-lambda-repository --force

$ aws lambda delete-function --function-name HelloPython

Serverless Frameworks

If using the AWS CLI seems like a lot of effort, there are frameworks like Serverless and Zappa that help you with a lot of the heavy lifting. Here are a few tutorials to get you started with Serverless and Zappa.