Use DescribeSubnets with an AWS SDK or CLI - Amazon Elastic Compute Cloud

Use DescribeSubnets with an AWS SDK or CLI

The following code examples show how to use DescribeSubnets.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// <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) { 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; }
CLI
AWS CLI

Example 1: To describe all your subnets

The following describe-subnets example displays the details of your subnets.

<userinput>aws ec2 describe-subnets</userinput>

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

For more information, see Working with VPCs and Subnets in the AWS VPC User Guide.

Example 2: To describe the subnets of a specific VPC

The following describe-subnets example uses a filter to retrieve details for the subnets of the specified VPC.

<userinput>aws ec2 describe-subnets \ --filters <replaceable>"Name=vpc-id,Values=vpc-3EXAMPLE"</replaceable></userinput>

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

For more information, see Working with VPCs and Subnets in the AWS VPC User Guide.

Example 3: To describe the subnets with a specific tag

The following describe-subnets example uses a filter to retrieve the details of those subnets with the tag CostCenter=123 and the --query parameter to display the subnet IDs of the subnets with this tag.

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

Output:

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

For more information, see Working with VPCs and Subnets in the Amazon VPC User Guide.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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"] }, ], }), );
  • For API details, see DescribeSubnets in AWS SDK for JavaScript API Reference.

PowerShell
Tools for PowerShell

Example 1: This example describes the specified subnet.

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

Example 2: This example describes all your subnets.

Get-EC2Subnet
  • For API details, see DescribeSubnets in AWS Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :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 self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" 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" self.key_pair_name = f"{resource_prefix}-key-pair" def get_subnets(self, vpc_id, zones): """ 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. """ try: response = self.ec2_client.describe_subnets( Filters=[ {"Name": "vpc-id", "Values": [vpc_id]}, {"Name": "availability-zone", "Values": zones}, {"Name": "default-for-az", "Values": ["true"]}, ] ) subnets = response["Subnets"] log.info("Found %s subnets for the specified zones.", len(subnets)) except ClientError as err: raise AutoScalerError(f"Couldn't get subnets: {err}") else: return subnets
  • For API details, see DescribeSubnets in AWS SDK for Python (Boto3) API Reference.

For a complete list of AWS SDK developer guides and code examples, see Create Amazon EC2 resources using an AWS SDK. This topic also includes information about getting started and details about previous SDK versions.