AWS Classroom Series – 02/Jul/2020

Creating an AWS Lambda with Environment and events using python

  • Create a blank function using python in aws lambda Preview
  • Lets build a simple calculator
{
    "op": add/sub,
    "val1": 5,
    "val2": 2

}
  • Now lets take the basic python code
import json

def lambda_handler(event, context):
    # TODO implement
    
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

  • Now lets modify the code to suit our problem statement
import json

def lambda_handler(event, context):
    op = event['op']
    val1 = event['val1']
    val2 = event['val2']
    result = 0
    if op == 'add':
        result = val1 + val2
    elif op == 'sub':
        result = val1 - val2
    elif op == 'mul':
        result = val1 * val2
    elif op == 'div':
        result = val1 // val2
    else:
        result = "Invalid"
        
        
    
    return {
        'statusCode': 200,
        'body': json.dumps(result)
    }

  • Now lets add the following logic to make use of environmental variables. I will be adding a ENVIRONMENTAL variable "DEBUG_LEVEL" which if it has value as verbose, we should print more logs Preview Preview
  • Now lets make changes in the code
import json
import os

def lambda_handler(event, context):
    debug_level = os.getenv('DEBUG_LEVEL')

    op = event['op']
    val1 = event['val1']
    val2 = event['val2']
    if debug_level == 'VERBOSE' :
        print("{} is operator and values are {} {}".format(op,val1,val2))
    result = 0
    if op == 'add':
        result = val1 + val2
    elif op == 'sub':
        result = val1 - val2
    elif op == 'mul':
        result = val1 * val2
    elif op == 'div':
        result = val1 // val2
    else:
        result = "Invalid"
    return {
        'statusCode': 200,
        'body': json.dumps(result)
    }
  • If you execute the function with environment varaible ‘DEBUG_LEVEL’ with value ‘VERBOSE’ you should see extra logs

  • Lambda can be exposed using API Gateways or Load balancers.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Customized Social Media Icons from Acurax Digital Marketing Agency

Discover more from Direct DevOps from Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading

Visit Us On FacebookVisit Us On LinkedinVisit Us On Youtube