AWS Boto3-如何使用多个过滤器并遍历标签名称/值?

问题描述

当前,我正在使用boto3两次调用AWS ec2,以获取以标签名org-production-*org-non-production-*开头的subnetID。如何在python中结合这两个功能,仍然能够访问SubnetID的all_prod_subnets和all_non_prod_subnets?我想避免重复代码仅对aws ec2进行一次调用,获取所有子网并对其进行迭代,然后根据标签名称过滤响应。

def get_all_production_subnets_from_accounts():
    subnet = vpc_client.describe_subnets(
        Filters=[{'Name': 'tag:Name','Values': ['org-production-*']}])['Subnets']
    if len(subnet) > 0:
        # print([s['SubnetId'] for s in subnet])
        all_prod_subnets =  [ s['SubnetId'] for s in subnet ]
        print("[DEBUG]Queried Subnet ID's of Production are: {}".format(all_prod_subnets))
        return all_prod_subnets
    else:
        return None

def get_all_nonproduction_subnets_from_acccounts():
    subnet = vpc_client.describe_subnets(
        Filters=[{'Name': 'tag:Name','Values': ['org-non-production-*']}])['Subnets']
    if len(subnet) > 0:
        # print([s['SubnetId'] for s in subnet])
        all_non_prod_subnets =  [ s['SubnetId'] for s in subnet ]
        print("[DEBUG]Queried Subnet ID's of Non-Production are: {}".format(all_non_prod_subnets))
        return all_non_prod_subnets
    else:
        return None

解决方法

一种方法如下:

def get_all_subnets_from_connectivity():

    subnets_found = {}
    
    # define subnet types of interest
    subnets_found['org-production'] = []
    subnets_found['org-non-production'] = []
    
    results = vpc_client.describe_subnets() 

    for subnet in results['Subnets']:

        if 'Tags' not in subnet:
            continue

        for tag in subnet['Tags']:

            if tag['Key'] != 'Name': continue
                
            for subnet_type in subnets_found:               
                if subnet_type in tag['Value']:
                    subnets_found[subnet_type].append(subnet['SubnetId'])

    return subnets_found



all_subnets = get_all_subnets_from_connectivity()


print(all_subnets)

示例输出:

{
'org-production': ['subnet-033bad31433b55e72','subnet-019879db91313d56a'],'org-non-production': ['subnet-06e3bc20a73b55283']
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...