Skip to main content

Overview

Subnets divide virtual networks into smaller, manageable segments. They enable network segmentation, security isolation, and efficient IP address management across both Azure and Google Cloud Platform.

Azure Subnets

Creating an Azure Subnet

API Endpoint

POST /api/azure/subnet/create
Content-Type: application/json

Request Body

{
  "subscriptionId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "rgName": "my-resource-group",
  "vnetName": "my-vnet",
  "subnetName": "web-subnet",
  "addressPrefix": "10.0.1.0/24"
}

Request Parameters

subscriptionId
string
required
Azure subscription ID containing the VNet
rgName
string
required
Resource group name where the VNet exists
vnetName
string
required
Virtual Network name where the subnet will be created
subnetName
string
required
Name for the new subnet
addressPrefix
string
default:"10.0.1.0/24"
CIDR block for the subnet (must be within VNet address space)

Implementation Details

Source: /workspace/source/project/backend/azure_modules/subnet.py:6
def subnet_create():
    credential = FlaskCredential()
    network_client = NetworkManagementClient(credential, subscription_id)
    
    poller = network_client.subnets.begin_create_or_update(
        rg,
        vnet,
        subnet_name,
        {"address_prefix": address_prefix}
    )
    result = poller.result()  # Wait for completion
Subnet creation in Azure uses an asynchronous operation that returns a poller. The implementation waits for completion before returning the response.

Response

Success (200):
{
  "message": "✅ Utworzono subnet: web-subnet w VNet: my-vnet",
  "subnet": "web-subnet"
}
Error (400):
{
  "error": "Brak wymaganych danych"
}
Error (401):
{
  "error": "Unauthorized"
}
Error (500):
{
  "error": "Detailed error from Azure SDK"
}

Azure Subnet Constraints

Address Prefix Must Fit: The subnet’s CIDR block must be within the VNet’s address space and not overlap with existing subnets.

Azure Reserved IPs

Azure reserves 5 IP addresses in each subnet:
AddressPurposeExample (10.0.1.0/24)
x.x.x.0Network address10.0.1.0
x.x.x.1Default gateway10.0.1.1
x.x.x.2Azure DNS mapping10.0.1.2
x.x.x.3Azure DNS mapping10.0.1.3
x.x.x.255Broadcast address10.0.1.255
Available IPs: For a /24 subnet (256 IPs), only 251 IPs are usable.

Common Azure Subnet Sizes

CIDRTotal IPsUsable IPsUse Case
/2983Gateway subnet (minimum)
/281611Small isolated workload
/273227Application Gateway
/266459Small application tier
/24256251Standard application tier
/23512507Large application tier
/2210241019Very large workload

Azure Subnet Listing

Subnets are automatically included when listing VNets: Source: /workspace/source/project/backend/azure_modules/vnet.py:31-32
for subnet in nt_client.subnets.list(rg_name, vnet_name):
    vnet_info["subnets"].append(subnet.name)

GCP Subnets

Creating a GCP Subnet

API Endpoint

POST /api/gcp/subnet/create
Content-Type: application/json

Request Body

{
  "projectId": "my-gcp-project",
  "region": "us-central1",
  "vpcName": "my-vpc",
  "subnetName": "us-central1-subnet",
  "ipCidrRange": "10.0.1.0/24"
}

Request Parameters

projectId
string
required
GCP project ID containing the VPC
region
string
required
GCP region where the subnet will be created (e.g., “us-central1”, “europe-west1”)
vpcName
string
required
VPC network name where the subnet will be created
subnetName
string
required
Name for the new subnet (must be unique within the region)
ipCidrRange
string
required
CIDR block for the subnet (e.g., “10.0.1.0/24”)

Implementation Details

Source: /workspace/source/project/backend/gcp/vpcs.py:133
def create_gcp_subnet():
    credentials = SessionCredentials(gcp_account)
    subnetworks_client = compute_v1.SubnetworksClient(credentials=credentials)
    
    network_url = f"projects/{project_id}/global/networks/{vpc_name}"
    
    subnet_resource = compute_v1.Subnetwork(
        name=subnet_name,
        ip_cidr_range=ip_cidr_range,
        network=network_url,
    )
    
    sub_create_request = compute_v1.InsertSubnetworkRequest(
        project=project_id,
        region=region,
        subnetwork_resource=subnet_resource,
    )
    
    operation = subnetworks_client.insert(request=sub_create_request)
    operation.result()  # Wait for completion
GCP subnets are regional resources. The subnet exists in a specific region and can be used by resources in any zone within that region.

Response

Success (201):
{
  "message": "Subnet 'us-central1-subnet' został pomyślnie utworzony w sieci 'my-vpc'."
}
Error (400):
{
  "error": "Pola 'projectId', 'region', 'vpcName', 'subnetName' oraz 'ipCidrRange' są wymagane."
}
Error (401):
{
  "error": "Nie znaleziono aktywnego konta GCP w sesji"
}
Error (403):
{
  "error": "Brak uprawnień do tworzenia subnetu w projekcie 'my-gcp-project' lub sieci 'my-vpc'. Szczegóły: ..."
}
Error (404):
{
  "error": "Sieć VPC 'my-vpc' nie została znaleziona w projekcie 'my-gcp-project'."
}
Error (409):
{
  "error": "Subnet o nazwie 'us-central1-subnet' już istnieje w regionie 'us-central1'."
}

GCP Subnet Constraints

Regional Scope: Each subnet is specific to a region. You cannot create a subnet that spans multiple regions.

GCP Reserved IPs

GCP reserves 4 IP addresses in each subnet:
AddressPurposeExample (10.0.1.0/24)
x.x.x.0Network address10.0.1.0
x.x.x.1Default gateway10.0.1.1
x.x.x.255Broadcast (not used but reserved)10.0.1.255
Second-to-lastReserved for future use10.0.1.254
Available IPs: For a /24 subnet (256 IPs), only 252 IPs are usable.

Common GCP Subnet Sizes

CIDRTotal IPsUsable IPsUse Case
/2984Minimal workload
/281612Small services
/273228Small application
/24256252Standard application
/23512508Large application
/2210241020Very large workload
/2040964092Enterprise-scale

GCP Subnet Listing

Subnets are aggregated across all regions when listing VPCs: Source: /workspace/source/project/backend/gcp/vpcs.py:35-39
subnet_request = compute_v1.AggregatedListSubnetworksRequest(project=project_id)
subnet_iterator = subnetworks_client.aggregated_list(request=subnet_request)

for region, response in subnet_iterator:
    if response.subnetworks:
        all_subnets_in_project[region] = list(response.subnetworks)
Source: /workspace/source/project/backend/gcp/vpcs.py:57-64
# Match subnets to their parent VPC
network_url_suffix = f"/{network.name}" 
for region, subnets_in_region in all_subnets_in_project.items():
    for subnet in subnets_in_region:
        if subnet.network.endswith(network_url_suffix):
            vpc_data["subnets"].append({
                "name": subnet.name,
                "region": region.split('/')[-1],
                "ipCidrRange": subnet.ip_cidr_range,
            })

Subnet Design Patterns

Three-Tier Architecture

Azure Example

VNet: prod-vnet (10.0.0.0/16)
├── frontend-subnet (10.0.1.0/24) - Web servers
├── backend-subnet (10.0.2.0/24) - Application servers
└── database-subnet (10.0.3.0/24) - Database servers

GCP Example

VPC: prod-vpc
├── us-central1-frontend (10.0.1.0/24) - Web tier
├── us-central1-backend (10.0.2.0/24) - App tier
└── us-central1-database (10.0.3.0/24) - Data tier

Multi-Region Deployment

GCP Regional Subnets

VPC: global-app-vpc
├── us-central1-app (10.1.0.0/20) - 4,092 IPs
├── europe-west1-app (10.2.0.0/20) - 4,092 IPs
└── asia-east1-app (10.3.0.0/20) - 4,092 IPs

Environment Segmentation

Azure Multi-Environment

VNet: dev-vnet (10.0.0.0/16)
├── dev-web (10.0.1.0/24)
├── dev-app (10.0.2.0/24)
└── dev-db (10.0.3.0/24)

VNet: prod-vnet (10.1.0.0/16)
├── prod-web (10.1.1.0/24)
├── prod-app (10.1.2.0/24)
└── prod-db (10.1.3.0/24)

IP Address Planning

Calculate Subnet Size

1

Count Resources

Estimate maximum number of VMs, containers, or services
2

Add Growth Buffer

Multiply by 1.5-2x for future growth
3

Account for Reserved IPs

Add 5 IPs (Azure) or 4 IPs (GCP) to the total
4

Choose CIDR

Select smallest CIDR block that fits requirements

Subnet Calculator

Example: Need 100 IP addresses in Azure
  1. Required IPs: 100
  2. With growth (2x): 200
  3. Plus reserved: 205
  4. Next power of 2: 256 IPs = /24 CIDR
  5. Result: Use 10.0.x.0/24

Avoid Overlapping

Ensure subnets don’t overlap, especially if you plan to:
  • Peer VNets/VPCs
  • Connect to on-premises networks
  • Set up VPN tunnels
Good Design:
Azure VNet: 10.0.0.0/16
├── 10.0.1.0/24
├── 10.0.2.0/24
└── 10.0.3.0/24

GCP VPC: 10.1.0.0/16
├── 10.1.1.0/24
├── 10.1.2.0/24
└── 10.1.3.0/24
Bad Design (overlapping):
Azure VNet: 10.0.0.0/16
└── 10.0.1.0/24

GCP VPC: 10.0.0.0/16  ❌ Overlaps with Azure!
└── 10.0.1.0/24       ❌ Same range!

Network Security

Azure Network Security Groups (NSGs)

Attach NSGs to subnets for traffic control:
Subnet: web-subnet
└── NSG: web-nsg
    ├── Allow HTTP (80) from Internet
    ├── Allow HTTPS (443) from Internet
    └── Deny all other inbound

GCP Firewall Rules

Firewall rules apply at VPC level but can target specific subnets:
VPC: prod-vpc
└── Firewall Rules
    ├── allow-http (target: web-subnet)
    ├── allow-ssh (target: admin-subnet)
    └── deny-all-ingress (priority: 65535)

Subnet-Specific Features

Azure Service Endpoints

Enable direct connectivity to Azure services:
  • Microsoft.Storage
  • Microsoft.Sql
  • Microsoft.KeyVault
  • Microsoft.ContainerRegistry

Azure Private Endpoints

Bring Azure PaaS services into your VNet:
  • Private IP address in subnet
  • No public endpoint needed
  • Traffic stays on Microsoft backbone

GCP Private Google Access

Allow instances without public IPs to reach Google APIs:
subnet_resource = compute_v1.Subnetwork(
    name=subnet_name,
    ip_cidr_range=ip_cidr_range,
    network=network_url,
    private_ip_google_access=True  # Enable Private Google Access
)

GCP Secondary IP Ranges

Define additional IP ranges for containers:
  • Primary range: VM instances
  • Secondary range 1: GKE pods
  • Secondary range 2: GKE services

Authentication Requirements

Azure

Source: /workspace/source/project/backend/azure_modules/subnet.py:7-8
if "access_token" not in session:
    return jsonify({"error": "Unauthorized"}), 401
Requires:
  • Active Azure session with access_token
  • Permissions: Microsoft.Network/virtualNetworks/subnets/write

GCP

Source: /workspace/source/project/backend/gcp/vpcs.py:134-139
accounts = session.get("accounts", [])
gcp_account = next((acc for acc in accounts if acc.get("provider") == "gcp"), None)

if not gcp_account or not gcp_account.get("refresh_token"):
    return jsonify({"error": "Authentication required"}), 401
Requires:
  • Active GCP session with refresh token
  • Permissions: compute.subnetworks.create

Best Practices

Plan for Growth: Always allocate more IP addresses than currently needed. It’s difficult to expand subnets later.
Use Consistent Naming: Adopt a naming convention like {region}-{tier}-{env} (e.g., “us-central1-web-prod”).
Document IP Allocation: Keep a spreadsheet or diagram showing which IP ranges are used where.
Cannot Modify CIDR: Once created, you cannot change a subnet’s IP range. You must delete and recreate.
Check VNet/VPC Space: Ensure the parent network has enough address space before creating subnets.

Troubleshooting

Azure: Subnet Creation Fails

Common Causes:
  1. Address prefix overlaps with existing subnet
  2. Address prefix outside VNet address space
  3. VNet doesn’t exist
  4. Invalid CIDR notation
Validation:
# Check VNet address space
ntclient.virtual_networks.get(rg_name, vnet_name).address_space

# List existing subnets
ntclient.subnets.list(rg_name, vnet_name)

GCP: Subnet Creation Fails

Common Causes:
  1. VPC doesn’t exist (404 error)
  2. Subnet name already used in region (409 error)
  3. IP range overlaps with existing subnet
  4. Missing permissions (403 error)
  5. Invalid region name
Validation:
# Check if VPC exists
networks_client.get(project=project_id, network=vpc_name)

# List existing subnets in region
subnetworks_client.list(project=project_id, region=region)

IP Address Exhaustion

Symptoms:
  • Cannot deploy new resources
  • “No available IP addresses” error
Solutions:
  1. Create additional subnet with new IP range
  2. Delete unused resources to free IPs
  3. Use smaller instance types if possible
  4. For GCP: Expand subnet IP range (supported)
  5. For Azure: Create new subnet (cannot expand existing)

Advanced Topics

Azure Subnet Delegation

Delegate subnets to specific Azure services:
  • Azure NetApp Files
  • Azure SQL Managed Instance
  • Azure Container Instances
  • Azure Databricks

GCP Subnet Expansion

GCP allows expanding subnet IP ranges:
# Expand from /24 to /23
subnet.ip_cidr_range = "10.0.1.0/23"  # Doubles available IPs
subnetworks_client.patch(...)
Azure doesn’t support subnet expansion. You must create a new subnet if you need more IP addresses.

Flow Logs

Azure: NSG Flow Logs
  • Capture IP traffic flow information
  • Store in Azure Storage
  • Analyze with Traffic Analytics
GCP: VPC Flow Logs
  • Enable at subnet level
  • Logs sent to Cloud Logging
  • Analyze with BigQuery

Comparison: Azure vs GCP Subnets

FeatureAzureGCP
ScopeVNet-specificVPC-specific, regional
Reserved IPs5 per subnet4 per subnet
ExpansionNot supportedSupported (expand only)
DefaultManual creationOptional auto-mode
Secondary RangesNot supportedSupported (for containers)
Private AccessService EndpointsPrivate Google Access
SecurityNSG at subnet levelFirewall rules at VPC level

Next Steps

Azure Networking

Deep dive into Azure VNet features

GCP Networking

Explore GCP VPC capabilities

Build docs developers (and LLMs) love