top of page

Two Part Serverless Lab - Part Two

Writer: Tyler WallTyler Wall

Updated: Feb 12


two part serverless labs part two


Two Part Serverless Lab - Part Two

You're going to want to have hands-on experience with both Azure and AWS as by far the two biggest players in Cloud computing. Our course Cloud Security NOW! covers getting hands-on with both of these platforms. We are going to work our way hands-on in this serverless lab part two


AWS, like Azure, offers you a free tier for signing up. Go ahead and get signed up with AWS.




Now that that's out of the way, let's get hands-on in your first AWS Cybersecurity Lab using AWS Lambda to execute a function for serverless computing.




Create a Lambda function with the console

In this example, your function takes a JSON object that contains two integer values labeled "length" and "width". The function multiplies these values to calculate an area and returns this as a JSON string.


Your function also prints the calculated area, along with the name of its CloudWatch log group. To create your function, you first use the console to create a basic Hello World function. Then you add your own function code.


To create a Hello World Lambda function with the console

  1. Open the Functions page of the Lambda console.

  2. Choose Create function.

  3. Select Author from scratch.

  4. In the Basic information pane, for Function name enter myLambdaFunction.

  5. For Runtime, choose Python 3.12

  6. Leave architecture set to x86_64 and choose Create function.


Lambda creates a function that returns the message Hello from Lambda! Lambda also creates an execution role for your function. An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. For your function, the role that Lambda creates grants basic permissions to write to CloudWatch Logs.


You now use the console's built-in code editor to replace the Hello world code that Lambda created with your own function code.


Choose the Code tab. In the console's built-in code editor, you should see the function code that Lambda created. If you don't see the lambda_function.py tab in the code editor, select lambda_function.py in the file explorer as shown on the following diagram.


Paste the following code into the lambda_function.py tab, replacing the code that Lambda created.


import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):

    # Get the length and width parameters from the event object.
    # The runtime converts the event object to a Python dictionary

    length=event['length']
    width=event['width']

    area = calculate_area(length, width)
    print(f"The area is {area}")
    logger.info(f"CloudWatch logs group: {context.log_group_name}")

    # return the calculated area as a JSON string
    data = {"area": area}
    return json.dumps(data)

def calculate_area(length, width):
    return length*width

Select Deploy to update your function's code. When Lambda has deployed the changes, the console displays a banner letting you know that it's successfully updated your function.


Understanding your function code

Before you move to the next step, let's take a moment to look at the function code and understand some key Lambda concepts.


The Lambda handler:Your Lambda function contains a Python function named lambda_handler. A Lambda function in Python can contain more than one Python function, but the handler function is always the entry point to your code. When your function is invoked, Lambda runs this method.


When you created your Hello world function using the console, Lambda automatically set the name of the handler method for your function to lambda_handler. Be sure not to edit the name of this Python function. If you do, Lambda won’t be able to run your code when you invoke your function.


The Lambda event object:The function lambda_handler takes two arguments, event and context. An event in Lambda is a JSON formatted document that contains data for your function to process.If your function is invoked by another AWS service, the event object contains information about the event that caused the invocation. For example, if an Amazon Simple Storage Service (Amazon S3) bucket invokes your function when an object is uploaded, the event will contain the name of the Amazon S3 bucket and the object key. In this example, you’ll create an event in the console by entering a JSON formatted document with two key-value pairs.


The Lambda context object:The second argument your function takes is context. Lambda passes the context object to your function automatically. The context object contains information about the function invocation and execution environment.

You can use the context object to output information about your function's invocation for monitoring purposes. In this example, your function uses the log_group_name parameter to output the name of its CloudWatch log group.


Logging in Lambda:With Python, you can use either a print statement or a Python logging library to send information to your function's log. To illustrate the difference in what's captured, the example code uses both methods. In a production application, we recommend that you use a logging library.


Invoke the Lambda function using the console

To invoke your function using the Lambda console, you first create a test event to send to your function. The event is a JSON formatted document containing two key-value pairs with the keys "length" and "width".


To create the test event

  1. In the Code source pane, choose Test.

  2. Select Create new event.

  3. For Event name enter myTestEvent.

  4. In the Event JSON panel, replace the default values by pasting in the following:

{
"length": 6,
"width": 7
}
  1. Choose Save.


You now test your function and use the Lambda console and CloudWatch Logs to view records of your function’s invocation.


To test your function and view invocation records in the console

In the Code source pane, choose Test. When your function finishes running, you’ll see the response and function logs displayed in the Execution results tab.


In this example, you invoked your code using the console's test feature. This means that you can view your function's execution results directly in the console. When your function is invoked outside the console, you need to use CloudWatch Logs.


To view your function's invocation records in CloudWatch Logs

  1. Open the Log groups page of the CloudWatch console.

  2. Choose the log group for your function (/aws/lambda/myLambdaFunction). This is the log group name that your function printed to the console.

  3. In the Log streams tab, choose the log stream for your function's invocation.


When you're finished working with the example function, delete it. You can also delete the log group that stores the function's logs, and the execution role that the console created.


To delete a Lambda function

  1. Open the Functions page of the Lambda console.

  2. Choose a function.

  3. Choose Actions, Delete.

  4. In the Delete function dialog box, enter delete, and then choose Delete.

To delete the log group

  1. Open the Log groups page of the CloudWatch console.

  2. Select the function's log group (/aws/lambda/my-function).

  3. Choose Actions, Delete log group(s).

  4. In the Delete log group(s) dialog box, choose Delete.

To delete the execution role

  1. Open the Roles page of the AWS Identity and Access Management (IAM) console.

  2. Select the function's execution role (for example, myLambdaFunction-role-31exxmpl).

  3. Choose Delete.

  4. In the Delete role dialog box, enter the role name and then choose Delete.





Tyler Wall CEO Cyber NOW Education

Tyler Wall is the founder of Cyber NOW Education. He holds bills for a Master of Science from Purdue University and also CISSP, CCSK, CFSR, CEH, Sec+, Net+, and A+ certifications. He mastered the SOC after having held every position from analyst to architect and is the author of three books, 100+ professional articles, four online courses, and regularly holds webinars for new cybersecurity talent.


You can connect with him on LinkedIn.


To view my dozens of courses, visit my homepage and watch the trailers!


Become a Black Badge member of Cyber NOW® and enjoy all-access for life.


Check out my latest book, Jump-start Your SOC Analyst Career: A Roadmap to Cybersecurity Success, winner of the 2024 Cybersecurity Excellence Awards.


Comments


bottom of page