Skip to content

Creating AWS Lambda function

Hovhannes Apinyan edited this page Apr 5, 2024 · 1 revision

Creating and Deploying a Python Lambda Function with Command Line Steps

Step 1: Writing the Lambda Function Code

  1. Create a Python File: In your preferred directory, create a Python file named lambda_function.py.
    touch lambda_function.py
  2. Edit the File: Open lambda_function.py in a text editor and write your Lambda function code.
    def lambda_handler(event, context):
        # Your code logic
        return {
            'statusCode': 200,
            'body': 'Hello from Lambda!'
        }

Step 2: Setting Up a Virtual Environment

  1. Create the Virtual Environment: In the directory where your Python file is, run:
    python3 -m venv venv
  2. Activate the Virtual Environment:
    source venv/bin/activate
  3. Install Dependencies: Install any needed libraries using pip.
    pip install requests  # Replace 'requests' with your required packages

Step 3: Preparing the Deployment Package

  1. Navigate to the Site-Packages Directory:
    cd venv/lib/python3.x/site-packages
    Replace python3.x with your specific Python version.
  2. Create the ZIP Archive:
    • Add the contents of the site-packages directory and your Python script to a ZIP file.
      zip -r9 ../../function.zip .
    • Move back to the project directory and add your Python file to the ZIP archive.
      cd ../../../
      zip -g function.zip lambda_function.py

Step 4: Creating the Lambda Function in AWS

  • Go to the AWS Management Console in your web browser.
  • Find and open the AWS Lambda service, either through the search bar or the services list.
  • Click on the Create function button to start the process of creating a new Lambda function.
  • Select Author from scratch.
  • Enter a name for your function in the Function name field.
  • In the Runtime dropdown, select the Python version that matches the one you used in your local environment.
  • Click on the Create function button at the bottom of the page to create your Lambda function’s basic configuration.

Step 5: Uploading the Function Code

  • Once your function is created, you will be taken to its configuration page.
  • Find the Code source section.
  • Click on Upload from, then select .zip file.
  • Use the file picker to locate and select the zip file you created earlier, which contains your function and its dependencies.
  • After selecting the file, click Save to upload your function code to AWS Lambda.

By following these steps, you have created a new Lambda function in AWS Lambda, configured its basic settings, and uploaded your Python code packaged in a zip file. Your Lambda function is now ready to be integrated with other AWS services or invoked directly.