Building Your First AWS Lambda Python Function

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

AWS Lambda is a compute service that runs code in response to events and automatically manages the compute resources required. In this tutorial, we’ll walk you through building your first AWS Lambda function from scratch as an example of how to use Amazon’s cloud computing platform.

The “aws lambda function python example” is a tutorial that teaches how to build your first AWS Lambda Python Function. It is an easy-to-follow guide with step-by-step instructions, and it has been designed for beginners.

Building Your First AWS Lambda Python Function

Developers create software. They shouldn’t have to be concerned about the infrastructure that supports that code. Thankfully, AWS cloud services such as Amazon Web Services’ AWS Lambda functions, often known as Lambda, allow businesses to focus on what they do best. You’ll learn how to get started with AWS Lambda and, more specifically, how to build up your first AWS Lambda Python in this article.

Stay tuned to discover how Lambda functions operate and how to put your newfound Lambda knowledge to use by creating a Lambda function and starting an EC2 instance using the Boto3 AWS Python SDK.

What’s the Big Deal About AWS Lambda Functions?

Let’s explore why Lambda is amazing and why you should do this in the first place before we get down to brass tax and start learning how to develop an AWS Lambda function in Python.

What exactly is Lambda?

AWS Lambda is a technology for serverless computing. The term’serverless’ refers to services that enable developers to execute code “without” the need of a server. There are a few different approaches to create a serverless application depending on the programming language you’re using. Python is one of the most frequent methods.

When the underlying server needs are ignored, developers are free to do what they do best: create code. Developers may test code and check how it works.

What is Lambda?

Using a serverless platform provides you certain unique capabilities that you won’t find anywhere else. These are some of the important abilities:

  • executing code in response to a response or event – Based on practically any AWS event, you may schedule code to execute at any time and as many times as you like. You don’t have to execute scripts on the fly anymore.
  • The code may be executed without an operating system — You don’t need to set up an environment to execute code using serverless functions. You won’t have to set up networking, virtual machines, storage, or anything else. You just need a location to execute code.
  • Lambda can run practically any sort of code, including Python, Node.JS, Ruby, Go, Java, C#, and even PowerShell.
  • Lambda’s servers are distributed over many availability zones in a region, providing built-in failover and fault tolerance.
  • Lambda functions are inexpensive. You just pay for the services you utilize. You may keep the code in a Lambda Function as long as you like. You are not charged as long as it is not in use.

AWS Lambda Python Programming Tutorial Overview

The remainder of this post will be a tutorial. Create a Lambda function to execute Python code to launch an EC2 instance in this comprehensive article. You’ll learn how to create a Lambda function that does the following:

  • Boto3 launches an EC2 instance using the Python SDK.
  • Creates a Boto3 code archive that can be run from Lambda.
  • Creates an S3 bucket in which the Boto3 code will be stored.
  • Boto3 is used to create a Lambda function.
  • The Lambda function is evaluated.
  • Creates an Amazon EC2 instance.

Prerequisites

You’ll need a few important objects and pieces of software to complete the work at hand if you want to follow along with the lesson.

  • An EC2 instance on AWS — This course does not need any extra equipment.
  • Python v3 — You can get Python here and install it. v3.7.6 will be used in all instances.
  • Your preferred code editor — Visual Studio Code with the Python plugin installed will be used in all examples. The screenshots will be different if you use a different coding editor.
  • An AWS profile is set up — The Boto3 Python library needs AWS credentials for the code you’ll be building. When you use the AWS CLI to configure a profile, the needed profile is created on the machine.
  • All examples assume you’ve previously established an IAM user and role with EC2FullAccess and LambdaFullAccess access.
  • AWS S3 bucket — See the AWS manual for details on how to build an S3 bucket. All of the examples in this post will utilize mynewbucket, an S3 bucket.
  • Install the boto3 Python package by typing pip install boto3 in a terminal window.

Using Python to Create an AWS EC2 Instance

In this example, regardless of whether you use Lambda or not, you must write some code to create an EC2 instance. Assume you have an EC2 instance that is only utilized for development. It doesn’t have to be turned on all the time. Instead of manually starting the instance, let’s write some code to do it for us.

You’ll write all of the code required to launch an EC2 instance using the Boto3 library in this part, so fire up Visual Studio Code or your preferred editor and get writing!

Boto3 Library Importing

Import the Boto3 library first. For this example, you’ll only need one library.

Boto3 Client Development

Boto3 must next establish a connection to the EC2 resource. The client() function will be used to do this. The client() function instructs Boto3 on which AWS service you want to use. You’ll connect to EC2 in this example.

Assign a variable named ec2 to the client. This object represents the EC2 connection from which you may launch the instance.

boto3.client(‘ec2’) = ec2

Developing a Python function

A Python function is required to execute the Boto3 code. There are two arguments in this function: event and context. The function you’re creating is now saved locally. However, this function will be delivered to AWS later and must comply with Lambda’s requirements. All Lambda functions have the event and context arguments by default.

  • The event parameter is an object that holds Lambda invoker information. The Lambda function is started by the invoker.
  • The context parameter is an object that provides information about the environment being constructed as well as the invocation, function, and execution environment.

The start of a function named start ec2instance is shown in the following excerpt (). This function may be named anything, but it will be used in all subsequent instances.

start ec2instance(event, context): define

After you’ve created the function, you’ll need to fill in the code inside it. This code really launches the EC2 instance when the Lambda executes.

You’ll see a placeholder for your instance id below. This is where you’ll put the ID of the EC2 instance from which the Lambda function will run. Please see these instructions for further information on getting an instance ID.

start ec2instance(event, context): define ec2.start_instances(InstanceIds= [‘your_instance_id’])

When you’re through with the code, you should have something like this:

import boto3 boto3.client(‘ec2’) = ec2 start ec2instance(event, context): define ec2.start_instances(InstanceIds= [‘your_instance_id’])

Save the script as start ec2instance.py to your PC now that the code has been created. It’ll come in handy in the following segment.

S3 uploading of the Python function

Lambda need a means to access the Python script after it has been built. AWS S3 is a popular location to store Lambda code.

The script must first be archived or compressed into a ZIP file before being uploaded. First, in your favorite method, build a ZIP archive containing the Python script. After that, upload the ZIP file to the S3 bucket you generated earlier in the Prerequisites section.

Putting Together a Lambda Build Function

You learnt how to write a Python script and upload it to an S3 bucket in the previous sections. You’ll utilize that Python in this step to create the Lambda function that will use it.

There’s a distinction to be made between the start ec2instance() function you established before, the function you’ll develop in this section, and an AWS Lambda Function (uppercase).

You wrote the Python code that the Lambda Function will use in the previous step. You’ll write the Python code for the Lambda Function in this section. The start ec2instance() function will be invoked by the Lambda Function when you write the code to construct it.

If you’re still in Visual Studio Code, create a new tab and save lambda build.py there. Let’s get started on building the Lambda function.

If you don’t want to see how the code works, copy the following piece and save it to your lambda build.py script. To continue, scroll down to the section Locally testing the Lambda Function.

Make that the placeholders [s3 bucket name] and [zip file name] are filled in with the correct values.

client = boto3.client(‘lambda’) def lambda build(): client = create lambda function create function(LambdafunctionName, Runtime=’python3.7′, Role=iamRole, Handler=’.lambda handler’, FunctionName=LambdafunctionName, Runtime=’python3.7′, Role=iamRo format(‘lambda build’), ‘Start a virtual machine,’ description=’ Code = ‘S3Key’:'[zip file name]’, ‘S3Bucket’:'[s3 bucket name]’)

Modules

Three Python modules are required for the Lambda function you’re writing:

  • The AWS Python SDK (boto3)
  • logging is a Python module for writing log messages.
  • sys — A typical Python module for passing arguments to the function during execution. This will be used in place of several input functions.

boto3 import logging import sys import

Creating the Lambda Function using Code

Begin by writing a lambda build Python function. This is not a required name for the function, but it will be used in all subsequent examples. Inside, use the client() function to create a variable named client. Instead of connecting to ec2, the code now connects to Lambda.

client = boto3.client(‘lambda’) def lambda build():

Run the create function() method once the client has been formed. The Lambda Function is created using the create function() method.

client.create function = create lambda function ()

There are a few needed arguments for the create function() method. The following are the parameters:

  • FunctionName — The Lambda function’s name. Because the first Python code built previously is named start ec2instance in this tutorial, be sure you utilize that name.
  • Python is used as the programming runtime for the Lambda function.
  • Role – The Role parameter requires the ARN. Please use this link to locate your ARN.
  • Handler – The Lambda handler function is used by Lambda to call a function in code. lambda build is the name of the function ().
  • Code – The code parameter specifies the location of the code. The start ec2instance.zip file prepared previously is saved in an S3 bucket in this tutorial.
  • Description — The name of the metadata description. Start a virtual machine, for example.

Make that the placeholders [s3 bucket name] and [zip file name] are filled in with the correct values.

client = create lambda function create function(FunctionName=LambdaFunctionName, Runtime=’python3.7′, Role=iamRole, Handler=’, FunctionName=LambdaFunctionName, Runtime=’python3.7 lambda handler’. format(‘lambda build’) , Code = ‘S3Bucket’:’s3 bucket name’, ‘S3Key’:’zip file name’, Description=’Start a virtual machine’)

You should now have a Python method called lambda build() that can create a Lambda function that looks like this:

lambda build(LambdaFunctionName, iamRole): lambda build(LambdaFunctionName, iamR boto3.client(‘lambda’) = client client = create lambda function create function(FunctionName=LambdaFunctionName, Runtime=’python3.7′, Role=iamRole, Handler=’, FunctionName=LambdaFunctionName, Runtime=’python3.7 lambda handler’. description=’Start a virtual machine’, format(‘lambda build’), Code = ‘S3Key’:’file name of zipped python code’, ‘S3Bucket’:’name of your s3 bucket’)

The Lambda Build Function is being executed.

Now that the build function has been constructed, you may write the code to call it. This is the code that will call the build function in order to generate the Lambda function.

Create two runtime parameters named FunctionName and Role, as shown in the following snippet, to call the build function you built previously.

lambda build(LambdaFunctionName, iamRole): lambda build(LambdaFunctionName, iamR

Then, using the sys module as input, add values to those parameters. You’ll supply arguments to the Lambda function when it finally executes. These arguments’ values will be stored in sys.argv[1] and sys.argv[2].

The sys library takes the parameter you specify and converts it to an argument runtime. Python will know in which order the arguments should be executed.

sys = lambdaFunctionName .argv[1] sys = iamRole .argv[2]

The only thing left is to call the Lambda construct function to generate the Lambda function itself once you’ve supplied parameter values.

lambda create (LambdaFunctionName, iamRole)

You will finally create a script named lambda build.py that will allow you to create the Lambda function.

boto3 import logging import sys import lambda build(LambdaFunctionName, iamRole): lambda build(LambdaFunctionName, iamR boto3.client(‘lambda’) = client client = create lambda function create function(FunctionName=LambdaFunctionName, Runtime=’python3.7′, Role=iamRole, Handler=’, FunctionName=LambdaFunctionName, Runtime=’python3.7 lambda handler’. description=’Start a virtual machine’, format(‘lambda build’), Code = ‘S3Key’:’file name of zipped python code’, ‘S3Bucket’:’name of your s3 bucket’) sys = lambdaFunctionName .argv[1] sys = iamRole .argv[2] lambda create (LambdaFunctionName, iamRole)

Locally testing the Lambda Function

You’ve finished writing the code that the Lambda function will run when it’s called. You’ve also written the code that will generate the Lambda function. Now we’ll run the Lambda build code to check whether a new Lambda function has been generated.

Open a terminal and go to the directory where the lambda build.py script was built before. To run the Python script that will generate the Lambda function, use the following command.

Make sure to replace the placeholder [lambda role arn] with the IAM role ARN you generated for this tutorial.

‘devlambda’ ‘[lambda role arn]’ python.lambda build.py

Navigate to the AWS console after the Python script has completed. Type Lambda into the Find Services search window and choose the Lambda option.

AWS Administration ConsoleAWS Administration Console

The Lamba should now be visible. A Lambda function named devlambda may be seen in the following screenshot. This is the name of the Lambda function that was supplied when the lambda build.py script was performed before.

‘devlambda’ ‘[lambda role arn]’ python.lambda build.py

devlambda Lamba Functiondevlambda Lamba Function

AWS Lambda Function Evaluation

In your AWS account, a Lambda function has been created. The difficult part is finished! Let’s put the Lambda function to the test.

Stop the EC2 Instance Demo

First, stop the EC2 instance the Lambda function is targeting. Remember that the start_ec2instance() function created earlier Creates an Amazon EC2 instance.. It doesn’t first ensure that it’s stopped. You must stop the EC2 instance to confirm the Lambda function will start it.

Modify the Runtime Parameters

Locate the Function code in your Lambda function. The start ec2instance() code from the previous start ec2instance.py script may be found there.

Replace lambda function.start ec2instance in the Handler information. Changing the Operator instructs Lambda to execute the start ec2instance.py script and the start ectinstance function ().

The function name is always listed after the script name.

Changing the OperatorChanging the Operator

Configure the Examination

Next, click the Test button in the accompanying snapshot to test the Lambda function.

Lambda Function EvaluationLambda Function Evaluation

If this is your first test, you will be presented with a screen that allows you to create a new one. Keep the default Hello World template since no inputs are required.

You will be requested to Create a Test Event if this is not your first time testing the Lambda. As indicated in the picture, keep all of the defaults and click the orange Create button.

Create a Test EventCreate a Test Event

Execute the Test

It’s here! This is the moment you’ve been looking forward to.

Now, choose the Test option. If the execution is successful, you will be alerted as indicated in the image below.

Button for Lambda TestingButton for Lambda Testing

Navigate to your EC2 instance to make sure the Lambda worked as expected. The EC2 instance you had previously stopped should again be operating!

Congrats! You’ve successfully launched a Lambda function on an EC2 instance!

Summary

In this blog article, you learned not only how to design a functional Lambda function, but also how to write the Python code required to make it work. You were able to execute code that altered your AWS environment using a serverless function with no infrastructure.

Take your understanding a step farther. Modify the Lambda function to trigger an AWS event using the same code supplied in this lesson; test starting the EC2 instance based on a CloudWatch event.

AWS Lambda is a serverless computing service that allows you to run code without provisioning or managing servers. The “aws lambda python dependencies” are the libraries and packages that your function will need in order to run.

Related Tags

  • aws lambda python project structure
  • hello world lambda function python
  • aws lambda python (boto3 example)
  • aws lambda python example github
  • create lambda function aws