Get All Server State of Your AWS Account via Lambda

Sometimes you need to find the servers state of all servers launched in your AWS Account. If you have only one region and few servers, you can get these details from AWS console very easily but if you have multiples server in multiple regions, then this task may create a problem. You have to check each region one-by-one to get the details.

Today, We will learn how to get these details via a simple lambda function. This lambda function will run and gives you all servers details and their states.

So, Let start:

1: Create an IAM role for lambda function with EC2 read-only permission.

You can check this link to learn, how to create IAM role for lambda.

2: Now, create a Lambda Function.

  • To create an Lambda Function, Go to Lambda service from AWS console and create a new Function.
    Lambda Console
  • Add Lambda Function name. (You can write any name).
  • In Runtime info, Choose "python 2.7".
  • In permission, Choose "Use an existing Role" in Execution Role
  • In Existing Role, choose the IAM role which you have create above for this Lambda Function.
  • Click on "Create Function".
  • Go to "Function Code" and Paste the below python code in it.
 1import boto3
 2
 3ec2 = boto3.client('ec2')
 4
 5def lambda_handler(event, context):
 6    ec2_regions = ec2.describe_regions()
 7    ec2_regions = ec2_regions['Regions']
 8
 9    for region in ec2_regions:
10        conn = boto3.resource('ec2', region_name = region['RegionName'])
11        instances = conn.instances.filter()
12        for instance in instances:
13            if instance.state["Name"] == "running"  or instance.state["Name"] == "stopped" :
14                print (instance.id, instance.instance_type, region['RegionName'], instance.state["Name"])
  • Change "Timeout" time to 2 min or 5 min.

  • Now, Save the function.

  • Lastly, test your Function. It will gives you all the details.

I ❤ AWS! Happy coding! 🧑‍💻 Enjoy #Cloudkaramchari