AWS Classroom notes – 12/08/2021

AWS Lambda functions

  • Lambda function to stop ec2 instances
import json
import boto3

print('Loading function')

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))
    name = event['Key']
    value = event['Value']
    instance_ids = get_ec2_instance_id(key=name, value=value)
    return instance_ids  # Echo back the first key value
    #raise Exception('Something went wrong')

def get_ec2_instance_id(key='Name', value='Web1'):
    ec2 = boto3.client('ec2')
    response = ec2.describe_instances(Filters = [
            'Name': f'tag:{key}',
            'Values': [
    instance_ids = []
    for reservation in response['Reservations']:
    return instance_ids

def stop_ec2(instance_ids=[]):
    ec2 = boto3.client('ec2')
        if len(instance_ids) > 0:
    except Exception as e:
  • Lambda function which will be triggered has the following syntax is reffered as handler
def lambda_handler(event, context):
  • The event is a dictionary which holds the values passed when triggering a lambda function
  • context is a bootstrap.LambdaContext which has information about the current function and other details Refer Here

Invoation Types

  • At a high level, lambda functions can be invoked using the following
    • A push: This is synchronous type of invocation where we make a request for the function to be invoked and wait for the function response.
    • An event: The asynchronous or event method for invoking functions is mainly used by other AWS services in the AWS ecosystem to prompt a lambda function as result of some action (example: when s3 object is uploaded invoke lambda function)
    • A Stream-based model

Event Sources

  • The following are the ways in which we can invoke a lambda function
    • Via AWS Lambda Invoke API Refer Here
    • By using SDK Refer Here. Refer invoke and invoke async methods in Client of lambda
    • Event Sources

Leave a Reply

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

About continuous learner

devops & cloud enthusiastic learner