【问题标题】:How to list the name of all AWS subnets using boto3如何使用 boto3 列出所有 AWS 子网的名称
【发布时间】:2017-04-29 10:59:07
【问题描述】:

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

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'])

我正在尝试以相同的方式列出所有子网名称:

print('Subnets:')
print('-------')
sn_all = ec2_client.describe_subnets()
for sn in sn_all['Subnets'] :
    print(sn['SubnetName'])

在这里,变量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'])

非常感谢任何帮助。

【问题讨论】:

    标签: amazon-web-services boto3 amazon-vpc


    【解决方案1】:

    Amazon VPC 子网没有“名称”字段(而安全组GroupName 字段)。

    在管理控制台中,您可以看到安全组有两列:组名称和名称。 Name 字段实际上是名为 Name 的标签的值。

    另一方面,子网只有名称标签。

    提示:查看可用信息的一种简单方法是查看AWS Command-Line Interface (CLI)describe-subnets 的文档。

    【讨论】:

    • @John Rotenstein - 谢谢你的回答。你是对的。所以,我必须使用名称标签。别无选择。
    • 嗨@Rafiq,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    • @John Rotenstein - 我不知道为什么我看不到接受你答案的选项!
    • @Rafiq,选择一个您认为是解决问题的最佳方法的答案。要将答案标记为已接受,请单击答案旁边的复选标记以将其从灰色切换为已填充。您可以随时更改接受的答案,或直接取消接受答案。
    • @John - 知道了。感谢您的跟进。
    【解决方案2】:
    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'])
    

    【讨论】:

    • 请添加一些关于您的代码的 cmets,它的作用以及它如何回答问题。
    • @CosminStaicu,它将为您提供您正在使用的区域的所有子网
    猜你喜欢
    • 2019-03-10
    • 2020-04-22
    • 1970-01-01
    • 2018-10-13
    • 2018-10-11
    • 2021-07-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多