DescribeSubnetsÚselo con una AWS SDK o CLI - Amazon Elastic Compute Cloud

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

DescribeSubnetsÚselo con una AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar DescribeSubnets.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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; } }
  • Para API obtener más información, consulte DescribeSubnetsla AWS SDK for .NET APIReferencia.

CLI
AWS CLI

Ejemplo 1: Describir todas las subredes

En el siguiente ejemplo de describe-subnets, se muestran los detalles de las subredes.

aws ec2 describe-subnets

Salida:

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

Para obtener más información, consulte Trabajo con subredes VPCs y subredes en la Guía del AWS VPC usuario.

Ejemplo 2: Para describir las subredes de una red específica VPC

En el siguiente describe-subnets ejemplo, se utiliza un filtro para recuperar los detalles de las subredes de la unidad especificada. VPC

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

Salida:

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

Para obtener más información, consulte Trabajar con subredes VPCs y subredes en la Guía del AWS VPCusuario.

Ejemplo 3: Describir las subredes con una etiqueta específica

En el siguiente describe-subnets ejemplo, se utiliza un filtro para recuperar los detalles de las subredes con la etiqueta CostCenter=123 y el --query parámetro para mostrar la subred IDs de las subredes con esta etiqueta.

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

Salida:

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

Para obtener más información, consulte Trabajar con subredes VPCs y subredes en la Guía del VPC usuario de Amazon.

  • Para API obtener más información, consulte DescribeSubnetsla Referencia de AWS CLI comandos.

JavaScript
SDKpara JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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"] }, ], }), );
  • Para API obtener más información, consulte DescribeSubnetsla AWS SDK for JavaScript APIReferencia.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se describe la subred especificada.

Get-EC2Subnet -SubnetId subnet-1a2b3c4d

Salida:

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

Ejemplo 2: En este ejemplo se describen todas las subredes.

Get-EC2Subnet
  • Para API obtener más información, consulte la referencia DescribeSubnetsde AWS Tools for PowerShell cmdlets.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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}")
  • Para API obtener más información, consulte DescribeSubnetsla AWS SDKreferencia de Python (Boto3). API

Para obtener una lista completa de guías para AWS SDK desarrolladores y ejemplos de código, consulte. Cree EC2 recursos de Amazon mediante un AWS SDK En este tema también se incluye información sobre cómo empezar y detalles sobre SDK las versiones anteriores.