How to retrieve VPC subnet ID and name with Pulumi?
TypeScriptYou can retrieve VPC subnet information using Pulumi's resource classes that interact with AWS networking infrastructure.
Below is a Pulumi program that retrieves a list of all subnets in a specified VPC. This is done using the
aws.ec2.getSubnetIds
function, which returns a list of all subnet IDs associated with a VPC. It then usesaws.ec2.getSubnet
to get details about each individual subnet, like its ID and name (provided it was given a name via tags).import * as pulumi from "@pulumi/pulumi"; import * as aws from "@pulumi/aws"; // Specify the ID of your VPC let vpcId = "<your-vpc-id>"; // Get a list of subnet IDs associated with the provided VPC ID let vpcSubnetIds = aws.ec2.getSubnetIds({ vpcId: vpcId }); // Log each subnet ID and name vpcSubnetIds.ids.then(ids => { ids.forEach(id => { let subnet = aws.ec2.getSubnet({ id: id }); subnet.then(s => console.log(`ID: ${s.id}, Name: ${s.tags!["Name"]}`)); }); });
Make sure to replace
"<your-vpc-id>"
with the actual ID of your VPC.Note that the subnet's name comes from the subnet's tags, specifically a tag named "Name". If a subnet does not have a "Name" tag, it is possible that
s.tags!["Name"]
could returnundefined
.This program should output the ID and name of each subnet within the specified VPC.