文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
DescribeSubnets
搭配 a AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 DescribeSubnets
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <summary> /// Get all the subnets for a Vpc in a set of availability zones. /// </summary> /// <param name="vpcId">The Id of the Vpc.</param> /// <param name="availabilityZones">The list of availability zones.</param> /// <returns>The collection of subnet objects.</returns> public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones) { try { var subnets = new List<Subnet>(); var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets( new DescribeSubnetsRequest() { Filters = new List<Amazon.EC2.Model.Filter>() { new("vpc-id", new List<string>() { vpcId }), new("availability-zone", availabilityZones), new("default-for-az", new List<string>() { "true" }) } }); // Get the entire list using the paginator. await foreach (var subnet in subnetPaginator.Subnets) { subnets.Add(subnet); } return subnets; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound") { _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist."); } throw; } catch (Exception ex) { _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}"); throw; } }
-
如需 API 詳細資訊,請參閱 DescribeSubnets AWS SDK for .NET 參考中的 API。
-
- CLI
-
- AWS CLI
-
範例 1:描述所有子網路
以下
describe-subnets
範例顯示子網路的詳細資訊。aws ec2 describe-subnets
輸出:
{ "Subnets": [ { "AvailabilityZone": "us-east-1d", "AvailabilityZoneId": "use1-az2", "AvailableIpAddressCount": 4089, "CidrBlock": "172.31.80.0/20", "DefaultForAz": true, "MapPublicIpOnLaunch": false, "MapCustomerOwnedIpOnLaunch": true, "State": "available", "SubnetId": "subnet-0bb1c79de3EXAMPLE", "VpcId": "vpc-0ee975135dEXAMPLE", "OwnerId": "111122223333", "AssignIpv6AddressOnCreation": false, "Ipv6CidrBlockAssociationSet": [], "CustomerOwnedIpv4Pool:": 'pool-2EXAMPLE', "SubnetArn": "arn:aws:ec2:us-east-2:111122223333:subnet/subnet-0bb1c79de3EXAMPLE", "EnableDns64": false, "Ipv6Native": false, "PrivateDnsNameOptionsOnLaunch": { "HostnameType": "ip-name", "EnableResourceNameDnsARecord": false, "EnableResourceNameDnsAAAARecord": false } }, { "AvailabilityZone": "us-east-1d", "AvailabilityZoneId": "use1-az2", "AvailableIpAddressCount": 4089, "CidrBlock": "172.31.80.0/20", "DefaultForAz": true, "MapPublicIpOnLaunch": true, "MapCustomerOwnedIpOnLaunch": false, "State": "available", "SubnetId": "subnet-8EXAMPLE", "VpcId": "vpc-3EXAMPLE", "OwnerId": "1111222233333", "AssignIpv6AddressOnCreation": false, "Ipv6CidrBlockAssociationSet": [], "Tags": [ { "Key": "Name", "Value": "MySubnet" } ], "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE", "EnableDns64": false, "Ipv6Native": false, "PrivateDnsNameOptionsOnLaunch": { "HostnameType": "ip-name", "EnableResourceNameDnsARecord": false, "EnableResourceNameDnsAAAARecord": false } } ] }
如需詳細資訊,請參閱 VPCs 使用者指南中的使用 Word 和子網路。 AWS VPC
範例 2:描述特定 VPC 的子網路
下列
describe-subnets
範例使用篩選條件來擷取指定 VPC 子網路的詳細資訊。aws ec2 describe-subnets \ --filters
"Name=vpc-id,Values=vpc-3EXAMPLE"
輸出:
{ "Subnets": [ { "AvailabilityZone": "us-east-1d", "AvailabilityZoneId": "use1-az2", "AvailableIpAddressCount": 4089, "CidrBlock": "172.31.80.0/20", "DefaultForAz": true, "MapPublicIpOnLaunch": true, "MapCustomerOwnedIpOnLaunch": false, "State": "available", "SubnetId": "subnet-8EXAMPLE", "VpcId": "vpc-3EXAMPLE", "OwnerId": "1111222233333", "AssignIpv6AddressOnCreation": false, "Ipv6CidrBlockAssociationSet": [], "Tags": [ { "Key": "Name", "Value": "MySubnet" } ], "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE", "EnableDns64": false, "Ipv6Native": false, "PrivateDnsNameOptionsOnLaunch": { "HostnameType": "ip-name", "EnableResourceNameDnsARecord": false, "EnableResourceNameDnsAAAARecord": false } } ] }
如需詳細資訊,請參閱 VPCs 使用者指南中的使用 Word 和子網路。 AWS VPC
範例 3:描述具有特定標籤的子網路
下列
describe-subnets
範例使用篩選條件來擷取具有 標籤的子網路詳細資訊,CostCenter=123
以及顯示具有此標籤之子網路的子網路 IDs--query
參數。aws ec2 describe-subnets \ --filters
"Name=tag:CostCenter,Values=123"
\ --query"Subnets[*].SubnetId"
\ --outputtext
輸出:
subnet-0987a87c8b37348ef subnet-02a95061c45f372ee subnet-03f720e7de2788d73
如需詳細資訊,請參閱 Amazon VPCs 使用者指南中的使用 Word 和子網路。 VPC
-
如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DescribeSubnets
。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const client = new EC2Client({}); const { Subnets } = await client.send( new DescribeSubnetsCommand({ Filters: [ { Name: "vpc-id", Values: [state.defaultVpc] }, { Name: "availability-zone", Values: state.availabilityZoneNames }, { Name: "default-for-az", Values: ["true"] }, ], }), );
-
如需 API 詳細資訊,請參閱 DescribeSubnets AWS SDK for JavaScript 參考中的 API。
-
- PowerShell
-
- for PowerShell 工具
-
範例 1:此範例說明指定的子網路。
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
輸出:
AvailabilityZone : us-west-2c AvailableIpAddressCount : 251 CidrBlock : 10.0.0.0/24 DefaultForAz : False MapPublicIpOnLaunch : False State : available SubnetId : subnet-1a2b3c4d Tags : {} VpcId : vpc-12345678
範例 2:此範例說明您的所有子網路。
Get-EC2Subnet
-
如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 DescribeSubnets。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class AutoScalingWrapper: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix: str, inst_type: str, ami_param: str, autoscaling_client: boto3.client, ec2_client: boto3.client, ssm_client: boto3.client, iam_client: boto3.client, ): """ Initializes the AutoScaler class with the necessary parameters. :param resource_prefix: The prefix for naming AWS resources that are created by this class. :param inst_type: The type of EC2 instance to create, such as t3.micro. :param ami_param: The Systems Manager parameter used to look up the AMI that is created. :param autoscaling_client: A Boto3 EC2 Auto Scaling client. :param ec2_client: A Boto3 EC2 client. :param ssm_client: A Boto3 Systems Manager client. :param iam_client: A Boto3 IAM client. """ self.inst_type = inst_type self.ami_param = ami_param self.autoscaling_client = autoscaling_client self.ec2_client = ec2_client self.ssm_client = ssm_client self.iam_client = iam_client sts_client = boto3.client("sts") self.account_id = sts_client.get_caller_identity()["Account"] self.key_pair_name = f"{resource_prefix}-key-pair" self.launch_template_name = f"{resource_prefix}-template-" self.group_name = f"{resource_prefix}-group" # Happy path self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" # Failure mode self.bad_creds_policy_name = f"{resource_prefix}-bc-pol" self.bad_creds_role_name = f"{resource_prefix}-bc-role" self.bad_creds_profile_name = f"{resource_prefix}-bc-prof" def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]: """ Gets the default subnets in a VPC for a specified list of Availability Zones. :param vpc_id: The ID of the VPC to look up. :param zones: The list of Availability Zones to look up. :return: The list of subnets found. """ # Ensure that 'zones' is a list, even if None is passed if zones is None: zones = [] try: paginator = self.ec2_client.get_paginator("describe_subnets") page_iterator = paginator.paginate( Filters=[ {"Name": "vpc-id", "Values": [vpc_id]}, {"Name": "availability-zone", "Values": zones}, {"Name": "default-for-az", "Values": ["true"]}, ] ) subnets = [] for page in page_iterator: subnets.extend(page["Subnets"]) log.info("Found %s subnets for the specified zones.", len(subnets)) return subnets except ClientError as err: log.error( f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}." ) error_code = err.response["Error"]["Code"] if error_code == "InvalidVpcID.NotFound": log.error( "The specified VPC ID does not exist. " "Please check the VPC ID and try again." ) # Add more error-specific handling as needed log.error(f"Full error:\n\t{err}")
-
如需 API 詳細資訊,請參閱 DescribeSubnets AWS SDK for Python (Boto3) Word 參考中的 API。
-