Skip to main content

NQE Query to enumerate AWS VPC subnets and allocation

  • 16 January 2024
  • 0 replies
  • 57 views

Keeping track of IP subnet allocation across multiple AWS accounts can be challenging. With NQE you can query all the VPCs at once.

The following NQE query list the root level CIDR blocks for each VPC, and then shows how the IP space is allocated across each subnet.

foreach cloudAccount in network.cloudAccounts
foreach vpc in cloudAccount.vpcs
foreach subnet in vpc.subnets
select {
cloudAccountName: cloudAccount.name,
vpcId: vpc.id,
ipv4CidrBlocks: vpc.ipv4CidrBlocks,
subnetId: subnet.id,
name: subnet.name,
tags: subnet.tags,
addresses: subnet.addresses,
region: subnet.region,
availabilityZone: subnet.availabilityZone
}

 This NQE goes even further, showing the UNALLOCATED IP space in each CIDR block. That is, the IP prefixes within each VPC that have NOT been assigned to a subnet:

/**
* @intent Find all unallocated IPv4 VPC CIDR blocks
* @description An unallocated CIDR block for a VPC is a CIDR block assigned to the VPC but not used by any subnet.
* The restriction to IPv4 is because the built-in function "ipAddressSet" only supports IPv4 subnets.
*/

keepIpv4Addresses(addresses) =
foreach address in addresses
let match = patternMatch(toString(address), `{ipv4Subnet}`)
where isPresent(match)
select address;

getAddresses(vpc) =
ipAddressSet(foreach subnet in vpc.subnets
foreach address in keepIpv4Addresses(subnet.addresses)
select address);

getSubnetValues(vpc) =
foreach subnet in vpc.subnets
foreach routeTable in vpc.routeTables
where routeTable.id == subnet.routeTableId
select {
subnet: ipAddressSet(keepIpv4Addresses(subnet.addresses)),
subnetName: subnet.name,
availabilityZone: subnet.availabilityZone,
routeTable: routeTable.name
};

foreach cloudAccount in network.cloudAccounts
foreach vpc in cloudAccount.vpcs
let rootCidrBlocks = ipAddressSet(keepIpv4Addresses(vpc.ipv4CidrBlocks))
let allocatedCidrBlocks = getAddresses(vpc)
let unallocatedCidrBlocks = rootCidrBlocks - allocatedCidrBlocks
foreach subnetValue
in getSubnetValues(vpc) +
{ subnet: unallocatedCidrBlocks,
subnetName: "UNALLOCATED",
availabilityZone: "",
routeTable: ""
}]
select {
"Cloud Account": cloudAccount.name,
VPC: vpc.name,
"VPC CIDR Blocks": rootCidrBlocks,
Subnet: subnetValue.subnet,
"Subnet Name": subnetValue.subnetName,
"Availability Zone": subnetValue.availabilityZone,
"Route Table": subnetValue.routeTable
}

 

Be the first to reply!

Reply