【问题标题】:BOTO3 : How to filter instance with tag "not equal" to something?BOTO3:如何过滤带有“不等于”标签的实例?
【发布时间】:2017-12-29 22:00:01
【问题描述】:

我们可以找到很多关于 ec2 过滤 wit boto3 的示例。 但我正在寻找一种解决方案来列出所有实例,除了带有特定标签的实例......

这怎么可能?

非常感谢

【问题讨论】:

标签: filter tags boto3


【解决方案1】:

自动应答(如果它对其他人有用...或被优化:))

import boto3
import logging

#define client connection
ec2c = boto3.client('ec2')
#define ressources connection
#ec2r = boto3.resource('ec2')

def lambda_handler(event, context):
    global ec2c
    global ec2r

    # Get list of regions
    regionslist = ec2c.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regionslist:
        print("=================================\n\n")
        print ("Looking at region %s " % region['RegionName'])
        reg=region['RegionName']

        # Connect to region
        #ec2r = boto3.setup_default_session(region_name=reg)
        ec2r = boto3.resource('ec2', region_name=reg)

        # get a list of all instances
        all_running_instances = [i for i in ec2r.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])]
        for instance in all_running_instances:
            print("Running instance : %s" % instance.id)

        # get instances with filter of running + with tag `Name`
        instances = [i for i in ec2r.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag:KeepMeAlive', 'Values':['Yes']}])]
        for instance in instances:
            print("Running instance with tag : %s" % instance.id)

        # make a list of filtered instances IDs `[i.id for i in instances]`
        # Filter from all instances the instance that are not in the filtered list
        instances_to_delete = [to_del for to_del in all_running_instances if to_del.id not in [i.id for i in instances]]

        # run over your `instances_to_delete` list and terminate each one of them
        for instance in instances_to_delete:
            instance.stop()
            print("Instance : %s stopped" % instance.id)
        print("=================================\n\n")

【讨论】:

    【解决方案2】:

    我刚找到这个:Shutdown EC2 instances that do not have a certain tag using Python

    但我忘了确切地说我想跨地区进行。 我想我需要使用 boto3.client 和 boto3.resource 但我不明白该怎么做。

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 2021-04-27
      • 2017-02-23
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      相关资源
      最近更新 更多