Azure Network Management Client Library
The Microsoft Azure Network Management Client Library for Python provides programmatic access to manage network resources within Azure subscriptions, including virtual networks, public IPs, network security groups, and more. It is part of the broader Azure SDK for Python and is currently at version 30.2.0, with regular updates aligning with Azure service API changes.
Common errors
-
(SubscriptionNotFound) The subscription 'xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' could not be found.
cause The provided subscription ID is incorrect, the authenticated principal does not have access to it, or the correct tenant is not selected for the current authentication context.fixVerify the subscription ID is correct and that the authenticated Azure principal (user or service principal) has the necessary permissions to the subscription. Ensure the correct Azure tenant is selected in your authentication context (e.g., via `az login` and `az account set` if using Azure CLI, or by setting `AZURE_TENANT_ID` environment variable). -
azure.core.exceptions.ResourceNotFoundError: (ResourceNotFound) The Resource 'Microsoft.Network/virtualNetworks/myVnet' under resource group 'myResourceGroup' was not found.
cause The Azure network resource (e.g., Virtual Network, Network Interface, Public IP) specified by its name, resource group, or resource type does not exist, has been deleted, or there is a typo in the provided details.fixDouble-check the resource name, resource group name, and ensure the resource type in your code matches the existing Azure resource. Confirm the resource exists in the specified subscription and region. If deploying with Azure Resource Manager templates, ensure any dependencies are correctly defined. -
ImportError: cannot import name 'NetworkManagementClient' from 'azure.mgmt.network.v20xx_yy_zz.network_management_client'
cause Starting with `azure-mgmt-network` version 23.0.0b2, API version subfolders and direct import of `NetworkManagementClient` from `v20xx_yy_zz.network_management_client` were removed as breaking changes.fixImport `NetworkManagementClient` directly from the top-level `azure.mgmt.network` package. ```python # Incorrect (old way) # from azure.mgmt.network.v2023_04_01.network_management_client import NetworkManagementClient # Correct (new way) from azure.mgmt.network import NetworkManagementClient ``` -
AttributeError: 'VirtualNetworksOperations' object has no attribute 'create_or_update'
cause Method names and object structures can change across major versions of `azure-mgmt-network` due to updates in the underlying Azure API. The `create_or_update` method for long-running operations like creating virtual networks was often renamed to `begin_create_or_update`.fixConsult the official `azure-mgmt-network` documentation or samples for version 30.2.0 to find the correct method signature. For many resource creation/update operations that are long-running, the method is prefixed with `begin_` (e.g., `begin_create_or_update`). ```python # Example for creating a virtual network from azure.identity import DefaultAzureCredential from azure.mgmt.network import NetworkManagementClient from azure.mgmt.network.models import VirtualNetwork, Subnet import os subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID") credential = DefaultAzureCredential() network_client = NetworkManagementClient(credential, subscription_id) resource_group_name = "myResourceGroup" location = "eastus" vnet_name = "myVnet" subnet_name = "mySubnet" vnet_parameters = VirtualNetwork( location=location, address_space={'address_prefixes': ['10.0.0.0/16']}, subnets=[Subnet(name=subnet_name, address_prefix='10.0.0.0/24')] ) # Use begin_create_or_update for long-running operations poller = network_client.virtual_networks.begin_create_or_update( resource_group_name, vnet_name, vnet_parameters ) vnet_result = poller.result() print(f"Created Virtual Network: {vnet_result.name}") ```
Warnings
- breaking Authentication method changes: The Azure SDK for Python (v20.0.0 and later) deprecated legacy credential classes like `ServicePrincipalCredentials` in `azure.common.credentials`. Modern authentication exclusively uses classes from `azure.identity` (e.g., `DefaultAzureCredential`).
- gotcha Long-Running Operations (LROs) now return a poller object. Operations like `create_or_update`, `delete`, and `begin_xyz` (prefixed) for resource provisioning or modification are asynchronous. They return an `LROPoller` object, not the final resource or `None` directly.
- breaking Significant API changes and refactoring occurred around v20.0.0. This includes changes to client method signatures, model classes, and how collection methods (`list`) are handled. Direct access to `.value` on list results is no longer necessary; iterators are returned.
- gotcha Azure SDK clients often require an Azure Subscription ID for proper operation. This ID must be provided either through the `AZURE_SUBSCRIPTION_ID` environment variable, or passed explicitly as an argument during client initialization or specific method calls.
- gotcha Missing AZURE_SUBSCRIPTION_ID: Many Azure SDK for Python operations and samples require the `AZURE_SUBSCRIPTION_ID` to be set as an environment variable or passed directly to client constructors/methods. Failure to provide it will result in warnings or errors during client initialization or resource operations.
Install
-
pip install azure-mgmt-network azure-identity
Imports
- NetworkManagementClient
from azure.mgmt.network import NetworkManagementClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.network import NetworkManagementClient
# Retrieve subscription ID from environment variable or replace with your ID
# You must set AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET
# (or use other authentication methods supported by DefaultAzureCredential)
SUBSCRIPTION_ID = os.environ.get("AZURE_SUBSCRIPTION_ID", "YOUR_SUBSCRIPTION_ID")
if SUBSCRIPTION_ID == "YOUR_SUBSCRIPTION_ID":
print("Warning: Please set the AZURE_SUBSCRIPTION_ID environment variable.")
print("Or replace 'YOUR_SUBSCRIPTION_ID' in the code with your actual ID.")
exit(1)
# Authenticate using DefaultAzureCredential (recommended for most scenarios)
try:
credential = DefaultAzureCredential()
# For local development, ensure Azure CLI is logged in, or relevant env vars are set
credential.get_token("https://management.azure.com/.default") # Test token acquisition
except Exception as e:
print(f"Authentication failed: {e}")
print("Please ensure you are logged into Azure CLI, have appropriate environment variables set,")
print("or use a different credential type.")
exit(1)
# Create a NetworkManagementClient instance
network_client = NetworkManagementClient(credential, SUBSCRIPTION_ID)
# Example: List all Public IP Addresses in the subscription
print("Listing Public IP Addresses...")
public_ips = network_client.public_ip_addresses.list_all()
for ip in public_ips:
print(f" - Name: {ip.name}, IP Address: {ip.ip_address or 'N/A'}, Resource Group: {ip.id.split('/')[4]}")
print("Public IP Address listing complete.")