如何使用 boto3 列出所有 AWS 子网的名称
How to list the name of all AWS subnets using 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'])
我正在尝试以相同的方式列出所有子网名称:
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 VPC 子网没有 "Name" 字段(而安全组 有 有 GroupName
字段)。
在管理控制台中,您可以看到安全组有两列:组名和名称。 Name
字段实际上是名为 Name 的标签的值。
另一方面,子网只有名称标签。
提示:查看可用信息的一种简单方法是查看 AWS Command-Line Interface (CLI) documentation for describe-subnets
.
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'])
我可以使用以下代码轻松列出所有安全组名称:
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 VPC 子网没有 "Name" 字段(而安全组 有 有 GroupName
字段)。
在管理控制台中,您可以看到安全组有两列:组名和名称。 Name
字段实际上是名为 Name 的标签的值。
另一方面,子网只有名称标签。
提示:查看可用信息的一种简单方法是查看 AWS Command-Line Interface (CLI) documentation for describe-subnets
.
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'])