简体   繁体   中英

AWS Boto3 - How to use multiple filters and iterate over Tag names/values?

Currently, I'm making two calls to AWS ec2 using boto3 to fetch subnetIDs that start with tag name org-production-* and org-non-production-* . How can I combine these two functions in python and still be able to access the SubnetID's all_prod_subnets and all_non_prod_subnets? I want to perhaps avoid code duplicatin make just one call to aws ec2, get all subnets and iterate them and filter the response based on tag name.

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

One way would be as follows:

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)

The example output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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