使用 AWS Lambda 计算正在运行和停止的 Ec2 实例 [英] Count Running and Stopped Ec2 Instances with AWS Lambda
问题描述
如何使用 boto3 和 AWS Lambda 函数计算特定区域中运行和停止的 EC2 实例的数量?
How can I count number of running and stopped EC2 instances in a particular region using boto3 and an AWS Lambda function?
推荐答案
这里有一些代码,用于检索实例列表并计算 stopped
和 running
实例的数量:
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'))
对ec2_resource.instances.all()
的调用检索所有实例的列表,并且有一个包含Name
state 属性> 状态.
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.
这将在 Lambda 函数的默认区域中运行.如果您想更改区域,请像这样指定区域名称:
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')
更新:如何通过 SNS 收到通知.
Update: How to be notified via SNS.
如果您想通过 SNS 收到通知,有两种选择:
If you want to be notified via SNS, there are two options:
- 让 Lambda 函数使用
publish(PhoneNumber='123')
命令,或 - 让 Lambda 函数使用
publish(TopicArn=xxx)
命令向 Amazon SNS 主题发送消息,然后通过首选方法(例如电子邮件、SMS)订阅 SNS 主题.
- 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.
这篇关于使用 AWS Lambda 计算正在运行和停止的 Ec2 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!