Step By Step to list all EC2 instance ids & regions using lambda function in amazon web service

Hello,I hope you’re doing well.

In this blog, we discuss how to display all EC2 instance ids and regions with the help of the lambda function on the aws console.Lambda is an event-oriented, server-free computing platform delivered by Amazon as part of Amazon Web Services.By using lambda,we can easily get information about the number of EC2 instances in each region.

There are some steps to display all ec2 instances using lambda function:

Launch a EC2 instance

  • Login to AWS console management.
  • Go to AWS Services & select Compute.
  • Click on EC2.
  • Click on the following below URL for launch a EC2 instance on aws console.

https://www.hackerxone.com/2021/05/21/how-create-ec2-instance-amazon-web-serviceaws/

Create a Lambda function

  • Go to Services & select Compute.
  • Click on Lambda.
  • Click on the following below URL for create a Lambda function.

https://www.hackerxone.com/2021/05/30/how-create-lambda-function-amazon-web-serviceaws/

  • Lambda function is created.

Attach a IAM policy on Lambda function Role

  • To attach the following IAM policy on Lambda function role.

“AmazonEC2FullAccess”

  • Here is the output.

Test Python code on lambda function for display all EC2 instance

  • Go to Created lambda function.

  • Under the test folder you will find a lambda_function.py file.Click in that file.

  • Remove the existing code.

  • Add the New code.

import json
import boto3
ec2list = []
def lambda_handler(event, context):
# Get list of regions
ec2 = boto3.client('ec2')
regions = ec2.describe_regions().get('Regions',[] )
# Iterate over regions
for region in regions:
print ("* Checking region %s " % region['RegionName'])
reg=region['RegionName']
client = boto3.client('ec2', region_name=reg)
response = client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
print ("Instance %s in %s" % (instance['InstanceId'], region['RegionName']))
ec2list.append(instance['InstanceId'])
return {
"statusCode": 200,
"body": ec2list

}

  • Click on Deploy.

  • Code is deployed.

Create a Event

A Event is a JSON object that mocks the structure of request emitted by AWS service to invoke a lambda function.

  • Next ,Click on Test.

  • Select event action “create a new event”.
  • Provide a Event Name.

  • Click on Save.

  • The Event was successfully saved.

Configure the Lambda function

  • Go to Configuration.
  • In the General configuration, click Edit.

  • By default the timeout is 3 sec.

  • Increase the timeout and click on Save.

  • Lambda function has been updated.

Test the code

  • Click on code option & click on Test.

  • Now, code is executed successfully.
  • Here is the output.

Leave a Reply