[Solved] Count Running and Stopped Ec2 Instances with AWS Lambda


Here’s some code that retrieves a list of instances and count the number of stopped and running instances:

import boto3

def lambda_handler(event, context):
    
    ec2_resource = boto3.resource('ec2')
    instances = [instance.state["Name"] for instance in ec2_resource.instances.all()]
    
    print('Running: ', instances.count('running'))
    print('Stopped: ', instances.count('stopped'))

The call to ec2_resource.instances.all() retrieves a list of all instances, and there is a state attribute that contains the Name of the state.

This will run in the default region for the Lambda function. If you wish to change regions, specify the region name like this:

ec2_resource = boto3.resource('ec2', region_name="ap-southeast-2")

Update: How to be notified via SNS.

If you want to be notified via SNS, there are two options:

  • Have the Lambda function directly send an SMS message to your phone via Amazon SNS using the publish(PhoneNumber="123") command, or
  • Have the Lambda function send a message to an Amazon SNS topic using the publish(TopicArn=xxx) command, and then subscribe to the SNS topic via the preferred method (eg email, SMS).

Please note that it will take a minute or so for instances to start/stop, so if you combine this with code that starts/stops instances, the count will not be accurate immediately after issuing those commands.

6

solved Count Running and Stopped Ec2 Instances with AWS Lambda