1. Packages
  2. AWS
  3. API Docs
  4. ec2
  5. getSubnets
AWS v7.11.0 published on Wednesday, Nov 5, 2025 by Pulumi

aws.ec2.getSubnets

Get Started
aws logo
AWS v7.11.0 published on Wednesday, Nov 5, 2025 by Pulumi

    This resource can be useful for getting back a set of subnet IDs.

    Example Usage

    The following shows outputting all CIDR blocks for every subnet ID in a VPC.

    import * as pulumi from "@pulumi/pulumi";
    import * as aws from "@pulumi/aws";
    import * as std from "@pulumi/std";
    
    const example = aws.ec2.getSubnets({
        filters: [{
            name: "vpc-id",
            values: [vpcId],
        }],
    });
    const exampleGetSubnet = example.then(example => std.toset({
        input: example.ids,
    })).then(invoke => .reduce((__obj, [__key, __value]) => ({ ...__obj, [__key]: aws.ec2.getSubnet({
        id: __value,
    }) })));
    export const subnetCidrBlocks = exampleGetSubnet.apply(exampleGetSubnet => Object.values(exampleGetSubnet).map(s => (s.cidrBlock)));
    
    import pulumi
    import pulumi_aws as aws
    import pulumi_std as std
    
    example = aws.ec2.get_subnets(filters=[{
        "name": "vpc-id",
        "values": [vpc_id],
    }])
    example_get_subnet = {__key: aws.ec2.get_subnet(id=__value) for __key, __value in std.toset(input=example.ids).result}
    pulumi.export("subnetCidrBlocks", [s.cidr_block for s in example_get_subnet])
    
    Example coming soon!
    
    using System.Collections.Generic;
    using System.Linq;
    using Pulumi;
    using Aws = Pulumi.Aws;
    using Std = Pulumi.Std;
    
    return await Deployment.RunAsync(() => 
    {
        var example = Aws.Ec2.GetSubnets.Invoke(new()
        {
            Filters = new[]
            {
                new Aws.Ec2.Inputs.GetSubnetsFilterInputArgs
                {
                    Name = "vpc-id",
                    Values = new[]
                    {
                        vpcId,
                    },
                },
            },
        });
    
        var exampleGetSubnet = Std.Toset.Invoke(new()
        {
            Input = example.Apply(getSubnetsResult => getSubnetsResult.Ids),
        }).Apply(invoke => );
    
        return new Dictionary<string, object?>
        {
            ["subnetCidrBlocks"] = exampleGetSubnet.Apply(exampleGetSubnet => (exampleGetSubnet).Values.Select(s => 
            {
                return s.CidrBlock;
            }).ToList()),
        };
    });
    
    Example coming soon!
    
    Example coming soon!
    

    The following example retrieves a set of all subnets in a VPC with a custom tag of Tier set to a value of “Private” so that the aws.ec2.Instance resource can loop through the subnets, putting instances across availability zones.

    import * as pulumi from "@pulumi/pulumi";
    import * as aws from "@pulumi/aws";
    import * as std from "@pulumi/std";
    
    export = async () => {
        const _private = await aws.ec2.getSubnets({
            filters: [{
                name: "vpc-id",
                values: [vpcId],
            }],
            tags: {
                Tier: "Private",
            },
        });
        const app: aws.ec2.Instance[] = [];
        for (const range of std.toset({
            input: _private.ids,
        }).result.map((v, k) => ({key: k, value: v}))) {
            app.push(new aws.ec2.Instance(`app-${range.key}`, {
                ami: ami,
                instanceType: aws.ec2.InstanceType.T2_Micro,
                subnetId: range.value,
            }));
        }
    }
    
    import pulumi
    import pulumi_aws as aws
    import pulumi_std as std
    
    private = aws.ec2.get_subnets(filters=[{
            "name": "vpc-id",
            "values": [vpc_id],
        }],
        tags={
            "Tier": "Private",
        })
    app = []
    for range in [{"key": k, "value": v} for [k, v] in enumerate(std.toset(input=private.ids).result)]:
        app.append(aws.ec2.Instance(f"app-{range['key']}",
            ami=ami,
            instance_type=aws.ec2.InstanceType.T2_MICRO,
            subnet_id=range["value"]))
    
    package main
    
    import (
    	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/ec2"
    	"github.com/pulumi/pulumi-std/sdk/go/std"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    func main() {
    pulumi.Run(func(ctx *pulumi.Context) error {
    private, err := ec2.GetSubnets(ctx, &ec2.GetSubnetsArgs{
    Filters: []ec2.GetSubnetsFilter{
    {
    Name: "vpc-id",
    Values: interface{}{
    vpcId,
    },
    },
    },
    Tags: map[string]interface{}{
    "Tier": "Private",
    },
    }, nil);
    if err != nil {
    return err
    }
    var app []*ec2.Instance
    for key0, val0 := range interface{}(std.Toset(ctx, &std.TosetArgs{
    Input: private.Ids,
    }, nil).Result) {
    __res, err := ec2.NewInstance(ctx, fmt.Sprintf("app-%v", key0), &ec2.InstanceArgs{
    Ami: pulumi.Any(ami),
    InstanceType: pulumi.String(ec2.InstanceType_T2_Micro),
    SubnetId: pulumi.Any(val0),
    })
    if err != nil {
    return err
    }
    app = append(app, __res)
    }
    return nil
    })
    }
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Pulumi;
    using Aws = Pulumi.Aws;
    using Std = Pulumi.Std;
    
    return await Deployment.RunAsync(async() => 
    {
        var @private = await Aws.Ec2.GetSubnets.InvokeAsync(new()
        {
            Filters = new[]
            {
                new Aws.Ec2.Inputs.GetSubnetsFilterInputArgs
                {
                    Name = "vpc-id",
                    Values = new[]
                    {
                        vpcId,
                    },
                },
            },
            Tags = 
            {
                { "Tier", "Private" },
            },
        });
    
        var app = new List<Aws.Ec2.Instance>();
        foreach (var range in )
        {
            app.Add(new Aws.Ec2.Instance($"app-{range.Key}", new()
            {
                Ami = ami,
                InstanceType = Aws.Ec2.InstanceType.T2_Micro,
                SubnetId = range.Value,
            }));
        }
    });
    
    package generated_program;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.aws.ec2.Ec2Functions;
    import com.pulumi.aws.ec2.inputs.GetSubnetsArgs;
    import com.pulumi.aws.ec2.Instance;
    import com.pulumi.aws.ec2.InstanceArgs;
    import com.pulumi.codegen.internal.KeyedValue;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.io.File;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(App::stack);
        }
    
        public static void stack(Context ctx) {
            final var private = Ec2Functions.getSubnets(GetSubnetsArgs.builder()
                .filters(GetSubnetsFilterArgs.builder()
                    .name("vpc-id")
                    .values(vpcId)
                    .build())
                .tags(Map.of("Tier", "Private"))
                .build());
    
            for (var range : KeyedValue.of(com.pulumi.std.StdFunctions(TosetArgs.builder()
                .input(private_.ids())
                .build()).result())) {
                new Instance("app-" + range.key(), InstanceArgs.builder()
                    .ami(ami)
                    .instanceType("t2.micro")
                    .subnetId(range.value())
                    .build());
            }
    
        }
    }
    
    resources:
      app:
        type: aws:ec2:Instance
        properties:
          ami: ${ami}
          instanceType: t2.micro
          subnetId: ${range.value}
        options: {}
    variables:
      private:
        fn::invoke:
          function: aws:ec2:getSubnets
          arguments:
            filters:
              - name: vpc-id
                values:
                  - ${vpcId}
            tags:
              Tier: Private
    

    Using getSubnets

    Two invocation forms are available. The direct form accepts plain arguments and either blocks until the result value is available, or returns a Promise-wrapped result. The output form accepts Input-wrapped arguments and returns an Output-wrapped result.

    function getSubnets(args: GetSubnetsArgs, opts?: InvokeOptions): Promise<GetSubnetsResult>
    function getSubnetsOutput(args: GetSubnetsOutputArgs, opts?: InvokeOptions): Output<GetSubnetsResult>
    def get_subnets(filters: Optional[Sequence[GetSubnetsFilter]] = None,
                    region: Optional[str] = None,
                    tags: Optional[Mapping[str, str]] = None,
                    opts: Optional[InvokeOptions] = None) -> GetSubnetsResult
    def get_subnets_output(filters: Optional[pulumi.Input[Sequence[pulumi.Input[GetSubnetsFilterArgs]]]] = None,
                    region: Optional[pulumi.Input[str]] = None,
                    tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
                    opts: Optional[InvokeOptions] = None) -> Output[GetSubnetsResult]
    func GetSubnets(ctx *Context, args *GetSubnetsArgs, opts ...InvokeOption) (*GetSubnetsResult, error)
    func GetSubnetsOutput(ctx *Context, args *GetSubnetsOutputArgs, opts ...InvokeOption) GetSubnetsResultOutput

    > Note: This function is named GetSubnets in the Go SDK.

    public static class GetSubnets 
    {
        public static Task<GetSubnetsResult> InvokeAsync(GetSubnetsArgs args, InvokeOptions? opts = null)
        public static Output<GetSubnetsResult> Invoke(GetSubnetsInvokeArgs args, InvokeOptions? opts = null)
    }
    public static CompletableFuture<GetSubnetsResult> getSubnets(GetSubnetsArgs args, InvokeOptions options)
    public static Output<GetSubnetsResult> getSubnets(GetSubnetsArgs args, InvokeOptions options)
    
    fn::invoke:
      function: aws:ec2/getSubnets:getSubnets
      arguments:
        # arguments dictionary

    The following arguments are supported:

    Filters List<GetSubnetsFilter>
    Custom filter block as described below.
    Region string
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    Tags Dictionary<string, string>
    Map of tags, each pair of which must exactly match a pair on the desired subnets.
    Filters []GetSubnetsFilter
    Custom filter block as described below.
    Region string
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    Tags map[string]string
    Map of tags, each pair of which must exactly match a pair on the desired subnets.
    filters List<GetSubnetsFilter>
    Custom filter block as described below.
    region String
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    tags Map<String,String>
    Map of tags, each pair of which must exactly match a pair on the desired subnets.
    filters GetSubnetsFilter[]
    Custom filter block as described below.
    region string
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    tags {[key: string]: string}
    Map of tags, each pair of which must exactly match a pair on the desired subnets.
    filters Sequence[GetSubnetsFilter]
    Custom filter block as described below.
    region str
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    tags Mapping[str, str]
    Map of tags, each pair of which must exactly match a pair on the desired subnets.
    filters List<Property Map>
    Custom filter block as described below.
    region String
    Region where this resource will be managed. Defaults to the Region set in the provider configuration.
    tags Map<String>
    Map of tags, each pair of which must exactly match a pair on the desired subnets.

    getSubnets Result

    The following output properties are available:

    Id string
    The provider-assigned unique ID for this managed resource.
    Ids List<string>
    List of all the subnet ids found.
    Region string
    Tags Dictionary<string, string>
    Filters List<GetSubnetsFilter>
    Id string
    The provider-assigned unique ID for this managed resource.
    Ids []string
    List of all the subnet ids found.
    Region string
    Tags map[string]string
    Filters []GetSubnetsFilter
    id String
    The provider-assigned unique ID for this managed resource.
    ids List<String>
    List of all the subnet ids found.
    region String
    tags Map<String,String>
    filters List<GetSubnetsFilter>
    id string
    The provider-assigned unique ID for this managed resource.
    ids string[]
    List of all the subnet ids found.
    region string
    tags {[key: string]: string}
    filters GetSubnetsFilter[]
    id str
    The provider-assigned unique ID for this managed resource.
    ids Sequence[str]
    List of all the subnet ids found.
    region str
    tags Mapping[str, str]
    filters Sequence[GetSubnetsFilter]
    id String
    The provider-assigned unique ID for this managed resource.
    ids List<String>
    List of all the subnet ids found.
    region String
    tags Map<String>
    filters List<Property Map>

    Supporting Types

    GetSubnetsFilter

    Name string
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    Values List<string>
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.
    Name string
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    Values []string
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.
    name String
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    values List<String>
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.
    name string
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    values string[]
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.
    name str
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    values Sequence[str]
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.
    name String
    Name of the field to filter by, as defined by the underlying AWS API. For example, if matching against tag Name, use:
    values List<String>
    Set of values that are accepted for the given field. Subnet IDs will be selected if any one of the given values match.

    Package Details

    Repository
    AWS Classic pulumi/pulumi-aws
    License
    Apache-2.0
    Notes
    This Pulumi package is based on the aws Terraform Provider.
    aws logo
    AWS v7.11.0 published on Wednesday, Nov 5, 2025 by Pulumi
      Meet Neo: Your AI Platform Teammate