繁体   English   中英

停止所有不包含AWS中带有单独值的标签的ec2实例

[英]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)

关键点:

  • 不要使用过滤器,而只需一次调用ec2.instances.all()。
  • 循环遍历实例,然后遍历标签,并使用和不使用进行计数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM