filter - BOTO3 : How to filter instance with tag "not equal" to something?

标签 filter tags boto3

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

这怎么可能?

非常感谢

最佳答案

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

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")

关于filter - BOTO3 : How to filter instance with tag "not equal" to something?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990827/

相关文章:

jquery - 在 jQuery 中过滤具有多个记录 ID 的分层 JSON 数据

javascript - JS - 通过正则表达式搜索带引号和不带引号的字符串

html - 什么会导致粗体标记 <b> 被忽略?

java - 单例标签接口(interface)

python - AWS : Python Script to Retrieve list of resources are currently in use

javascript - React 中的过滤器列表

java - 使用条件转换 HashMap 中的 Stream

ios - 如何在 iOS 中获取多个 ScrollView 的索引

node.js - 使用 AWS SDK Node.js 的自定义 S3 服务器的自签名证书错误

python - 诊断 boto3 中的内存泄漏