Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

python - Count Running and Stopped Ec2 Instances with AWS Lambda

How can I count number of running and stopped EC2 instances in a particular region using boto3 and an AWS Lambda function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...