AWS lambda python 函数 - 停止具有特定标记的虚拟机



我创建了一个 lampda 函数来停止具有特定标签的 ec2 实例,python 代码如下所示。此解决方案的主要任务是停止所有带有标签"名称:目的,值:临时">的实例。当我执行此脚本时,所有 ec2 实例都将停止。我想以下过滤器instances = ec2.instances.filter(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}])有问题. 函数代码如下:

import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
ec2 = boto3.resource('ec2',region_name=region)
instances = ec2.instances.filter(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}])
RunningInstances = [instance.id for instance in instances]
for i in RunningInstances:
stoppingInstances = ec2.instances.stop(i)

您的标签过滤器是错误的,您需要更改它:

filters = [{
'Name': 'tag:Name',
'Values': ['Shut']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]

这是完整的工作示例:

import boto3
#define the connection
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:Name',
'Values': ['Shut']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances
instances = ec2.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
#print the instances for logging purposes
#print RunningInstances
#make sure there are actually instances to shut down.
if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(
InstanceIds=RunningInstances).stop()
print(shuttingDown)
else:
print("No Instances to shut down")

试试这段代码。我做了一个小改动

import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
ec2_regions = [region['RegionName'] for region in client.describe_regions(['Regions']]
for region in ec2_regions:
ec2 = boto3.resource('ec2',region_name=region)
instances = ec2.describe_instances(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}]) #you can try by adding describe_instances()
RunningInstances = [instance.id for instance in instances]
for i in RunningInstances:
stoppingInstances = ec2.instances.stop(i)

相关内容

  • 没有找到相关文章

最新更新