如何使用 boto3 列出所有 AWS 子网的名称

Raf*_*fiq 3 amazon-web-services amazon-vpc boto3

我可以使用以下代码轻松列出所有安全组名称:

import boto3
ec2_client = boto3.client('ec2')

print('All Security Groups:')
print('----------------')
sg_all = ec2_client.describe_security_groups()
for sg in sg_all['SecurityGroups'] :
    print(sg['GroupName'])
Run Code Online (Sandbox Code Playgroud)

我试图以相同的方式列出所有子网名称,例如:

print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    print(sn['SubnetName'])
Run Code Online (Sandbox Code Playgroud)

在这里,变量sn获取所有每个子网,包括所有属性和标签,但无法找到子网的正确属性名称,例如GroupName.

我可以使用 boto3.resource('ec2') 或以下代码,但为了简单起见,我正在寻找上面使用的类似方法来列出所有安全组:

print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    for tag in sn['Tags']:
        if tag['Key'] == 'Name':
            print(tag['Value'])
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏。

小智 7

import boto3
ec2_client = boto3.client('ec2')
print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    print(sn['SubnetId'])
Run Code Online (Sandbox Code Playgroud)

  • 请添加一些关于您的代码、它的作用以及它如何回答问题的评论。 (2认同)