AWS (Amazon Web Services) Lambda Function

Utkarsh GuptaUtkarsh Gupta
4 min read

AWS Lambda

When we talk about lambda, then lambda just a Executor which takes code as an input submitted to the aws lambda and lambda executes and provides the output after executing the code. This code can be form of python, java, node.js, PowerShell, Go, C#.

Advantages using aws lambda:

No server setup

no need to start or stop

No additional cost

serverless

Integrates with other AWS Services: AWS lambda can be integrated with different AWS services like the following :

API Gateway, DynamoDB, S3, Step Functions, SNS, SQS.

How Does AWS (Amazon Web Services) Lambda Functions Work?

Start off by uploading the code to AWS Lambda. From there, set up the code to trigger from other AWS services, HTTP endpoints, or mobile apps. AWS Lambda will only run the code when it’s triggered and will also only use the computing resources needed to run it. The user has to pay only for the compute time used.

In this Lab,

Step 1: We create a EC2 instance in various regions

Step 2: Create a role of Lambda with EC2 access permission

Step 3: Run the program to take a snapshots of all instances running in the various regions, program written in Python languages in 3.8 version

Step 4: Allocate RAM and TTL to run the program

Step 5: We see the snapshots of all instances in various regions.

We create a EC2 instance in various regions

  1. Created a instance in Ohio region (us-east-2c) AZ, which is running state

  1. Created a instance in N.virginia region (us-east-1e) AZ, which is running state

Create a role of Lambda with EC2 access permission

Under IAM, Click on Roles and then click "Create role"

Put the roles name :

Click the role which you created earlier, check the all details:

Creating AWS (Amazon Web Services) Lambda Functions

Step 1: Log in to your AWS console and search for Lambda. As shown in the following image and Click on "Create function"

Step 2: Here we are going to use Author from scratch and configure the details according to your requirement.

Step 3: In Execution role, we are using existing role which we created in above step Role name:(My-lambda-rule-for-Ec2)

Step 4: Successfully our function is created.

Step 5: We share this python code for Lambda Function.

# Backup all in-use volumes in all regions

import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')

    # Get list of regions
    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regions:
        print("Checking region %s " % region['RegionName'])
        reg=region['RegionName']

        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)

        # Get all in-use volumes in all regions  
        result = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])

        for volume in result['Volumes']:
            print("Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone']))

            # Create snapshot
            result = ec2.create_snapshot(VolumeId=volume['VolumeId'],Description='Created by Lambda backup function ebs-snapshots')

            # Get snapshot resource 
            ec2resource = boto3.resource('ec2', region_name=reg)
            snapshot = ec2resource.Snapshot(result['SnapshotId'])

            volumename = 'N/A'

            # Find name tag for volume if it exists
            if 'Tags' in volume:
                for tags in volume['Tags']:
                    if tags["Key"] == 'Name':
                        volumename = tags["Value"]

            # Add volume name to snapshot for easier identification
            snapshot.create_tags(Tags=[{'Key': 'Name','Value': volumename}])Step 6: In "Deploy"  copy the above code and paste here/

Step 6 : Copy the above code and paste in code source and click on "Deploy"

Allocate RAM and TTL to run the program

Under configuration click "Edit"

Configure the test event

Go back to code section, click on "Test"

Now, test event was successfully saved.

Click on "Test" and then, Execution started...

It start checking all the regions, wherever your instance showing running, it took a backup in that region.

We see the snapshots of all instances in various regions.

  1. In Ohio region, we see the lambda created a backup.

  2. In N.Virginia region, we see the lambda created a backup.

0
Subscribe to my newsletter

Read articles from Utkarsh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Utkarsh Gupta
Utkarsh Gupta

πŸš€ Hi everyone! I'm Utkarsh Gupta, IAM Consultant. I am very passionate for all things DevOps. Right now, I'm learning and working on some cool projects and I can't wait to share what I'm learning with you all! πŸ› οΈ Here's what's in my toolbox: Linux Docker Kubernetes Jenkins AWS Python Prometheus Grafana Ansible Terraform Join me as we explore AWS DevOps together. Let's learn and grow together in this ever-changing field! 🀝 Feel free to connect with me for: Sharing experiences Friendly chats Learning together Follow my journey on Hashnode and LinkedIn for daily updates. Let's dive into the world of DevOps together! πŸš€ #DevOps #AWS #DevOpsJourney #90DaysOfDevOps