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

时间:2019-02-18 06:45:59

标签: aws-lambda boto3

我需要在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")

1 个答案:

答案 0 :(得分:0)

正如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()进行一次调用即可。
  • 遍历实例,然后遍历标签,并在有无计数的情况下进行计数。