Python AWS Boto3-如何使用多个过滤器并迭代标记名/值?
目前,我正在使用boto3对AWS ec2进行两次调用,以获取以标记名Python AWS Boto3-如何使用多个过滤器并迭代标记名/值?,python,amazon-ec2,pytest,boto3,amazon-vpc,Python,Amazon Ec2,Pytest,Boto3,Amazon Vpc,目前,我正在使用boto3对AWS ec2进行两次调用,以获取以标记名org production-*和org non production-*开头的子网。如何在python中组合这两个函数,并且仍然能够访问子网的所有生产子网和所有非生产子网?我想避免代码重复,只需调用一次aws ec2,获取所有子网并迭代它们,然后根据标记名过滤响应 def get_all_production_subnets_from_accounts(): subnet = vpc_client.describe_
org production-*
和org non production-*
开头的子网。如何在python中组合这两个函数,并且仍然能够访问子网的所有生产子网和所有非生产子网?我想避免代码重复,只需调用一次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']
}
一种方法如下:
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']
}