
[英]How to Stop EC2 instances automatically without specific tag and value
[英]Stop all ec2 instances that does not contains a tag with a sepecific value in AWS
我需要在Python中为AWS lambda函数编写脚本,以停止所有没有特定标签或该标签没有特定值的ec2实例。
我正在将boto3与python一起使用以获取所有实例,并使用filter过滤具有该特定标签或其标签值的所有实例,但无法获取没有该特定标签或其值而运行的实例。
import boto3
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
filters = [{
'Name': 'tag:state:scheduleName',
'Values': ['24x7']
}]
#get all instances
AllInstances=[instance.id for instance in ec2.instances.all()]
# get instances with that tag and value
instances = ec2.instances.filter(Filters=filters)
RunningInstancesWithTag = [instance.id for instance in instances]
RunningInstancesWithoutTag= [x for x in AllInstances if x not in RunningInstancesWithTag]
if len(RunningInstancesWithoutTag) > 0:
print("found instances with out tag")
ec2.instances.filter(InstanceIds = RunningInstancesWithoutTag).stop() #for stopping an ec2 instance
print("instance stopped")
else:
print("let it be run as tag value is 24*7")
正如John在评论中建议的那样,您使用过滤器将其复杂化了。
您想要这样的东西:
import boto3
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
running_with = []
running_without = []
for instance in ec2.instances.all():
if instance.state['Name'] != 'running':
continue
has_tag = False
for tag in instance.tags:
if tag['Key'] == 'scheduleName' and tag['Value'] == '24x7':
has_tag = True
break
if has_tag:
running_with.append(instance.id)
else:
running_without.append(instance.id)
print("With: %s" % running_with)
print("Without: %s" % running_without)
关键点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.