Gunakan DescribeSubnets dengan AWS SDK atau CLI - Amazon Elastic Compute Cloud

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan DescribeSubnets dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanDescribeSubnets.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; } }
  • Untuk API detailnya, lihat DescribeSubnetsdi AWS SDK for .NET APIReferensi.

CLI
AWS CLI

Contoh 1: Untuk menjelaskan semua subnet Anda

Contoh describe-subnets berikut menampilkan detail subnet Anda.

aws ec2 describe-subnets

Output:

{ "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 } } ] }

Untuk informasi selengkapnya, lihat Bekerja dengan VPCs dan Subnet di Panduan AWS VPC Pengguna.

Contoh 2: Untuk menggambarkan subnet tertentu VPC

describe-subnetsContoh berikut menggunakan filter untuk mengambil rincian untuk subnet yang ditentukan. VPC

aws ec2 describe-subnets \ --filters "Name=vpc-id,Values=vpc-3EXAMPLE"

Output:

{ "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 } } ] }

Untuk informasi selengkapnya, lihat Bekerja dengan VPCs dan Subnet di Panduan AWS VPC Pengguna.

Contoh 3: Untuk menjelaskan subnet dengan tanda tertentu

describe-subnetsContoh berikut menggunakan filter untuk mengambil rincian subnet tersebut dengan tag CostCenter=123 dan --query parameter untuk menampilkan subnet subnet IDs dengan tag ini.

aws ec2 describe-subnets \ --filters "Name=tag:CostCenter,Values=123" \ --query "Subnets[*].SubnetId" \ --output text

Output:

subnet-0987a87c8b37348ef subnet-02a95061c45f372ee subnet-03f720e7de2788d73

Untuk informasi selengkapnya, lihat Bekerja dengan VPCs dan Subnet di Panduan VPC Pengguna Amazon.

JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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"] }, ], }), );
  • Untuk API detailnya, lihat DescribeSubnetsdi AWS SDK for JavaScript APIReferensi.

PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini menjelaskan subnet yang ditentukan.

Get-EC2Subnet -SubnetId subnet-1a2b3c4d

Output:

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

Contoh 2: Contoh ini menjelaskan semua subnet Anda.

Get-EC2Subnet
  • Untuk API detailnya, lihat DescribeSubnetsdi AWS Tools for PowerShell Referensi Cmdlet.

Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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}")

Untuk daftar lengkap panduan AWS SDK pengembang dan contoh kode, lihatMembuat EC2 sumber daya Amazon menggunakan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang SDK versi sebelumnya.