Azure Service Bus Management Client Library
The `azure-mgmt-servicebus` library provides the client-side functionality for managing Azure Service Bus resources, such as namespaces, queues, and topics, through the Azure Resource Manager API. It is part of the broader Azure SDK for Python, currently at version 9.0.0, and follows a consistent release cadence with other Azure management libraries, typically updated monthly or bi-monthly with new API versions and features.
Common errors
-
ModuleNotFoundError: No module named 'azure.mgmt.servicebus'
cause The `azure-mgmt-servicebus` package has not been installed or the Python environment where the code is run does not have access to it.fixInstall the package using pip: `pip install azure-mgmt-servicebus azure-identity` -
ClientAuthenticationError: (InvalidAuthenticationToken) The access token is invalid.
cause The credentials provided to `ServiceBusManagementClient` are incorrect, expired, or lack the necessary permissions to perform the requested operation on the Azure Service Bus resources. This often happens with incorrect environment variables for `DefaultAzureCredential` or an improperly configured Service Principal.fixEnsure that the environment variables `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_SUBSCRIPTION_ID` are correctly set for `DefaultAzureCredential` or that the `TokenCredential` object has the required 'Azure Service Bus Data Owner' or 'Azure Service Bus Data Sender/Receiver' role assignments. -
(ResourceGroupNotFound) Resource group 'your_resource_group_name' could not be found.
cause The specified resource group name in the management operation does not exist, is misspelled, or the authenticated principal does not have permission to view it in the given subscription.fixVerify the resource group name is correct in the Azure portal or via Azure CLI (`az group list`). Ensure the authenticated identity has at least 'Reader' role on the subscription or 'Contributor' role on the resource group. -
from azure.servicebus.control_client import ServiceBusService
cause This import statement refers to an older, deprecated version (0.50 or lower) of the Azure Service Bus client library, which has been replaced by newer versions with different APIs.fixFor management operations (creating/deleting queues/topics/subscriptions), use `from azure.mgmt.servicebus import ServiceBusManagementClient`. For sending and receiving messages, use `from azure.servicebus import ServiceBusClient, ServiceBusMessage` (from the `azure-servicebus` package). -
The property 'RequiresDuplicateDetection' can't be set when creating a Queue because the namespace 'your_namespace' is using the 'Basic' Tier.
cause You are attempting to configure a feature (like duplicate detection, sessions, or larger message sizes) that is not supported by the Basic tier of Azure Service Bus. These features are only available in the Standard or Premium tiers.fixUpgrade your Azure Service Bus namespace to the Standard or Premium tier, or remove the unsupported configuration properties from your queue or topic creation parameters.
Warnings
- breaking Major versions of Azure Management SDKs, especially from v7 onwards, introduced significant breaking changes. These often include the separation of synchronous and asynchronous clients, changes to method signatures (e.g., keyword-only arguments), and updates to model object structures. Upgrading from versions older than 7.x.x typically requires substantial code modification.
- gotcha This library (`azure-mgmt-servicebus`) is strictly for *managing* Service Bus resources (creating namespaces, queues, topics, etc.). It does *not* provide functionality for sending or receiving messages from Service Bus queues or topics. For data plane operations, you need to use the `azure-servicebus` library.
- gotcha Authentication mechanisms have evolved. Older examples might use `ServicePrincipalCredentials` directly, which is now deprecated. The recommended approach is `azure-identity` (e.g., `DefaultAzureCredential`), which provides a unified way to authenticate across different Azure environments.
- gotcha Listing operations often return paginated iterators rather than a simple list. While these can often be iterated directly, for scenarios requiring explicit page-by-page processing (e.g., handling large result sets, tracking continuation tokens), you may need to use `by_page()` methods if available or handle the iterator carefully.
- gotcha The Azure Management SDKs often require the `AZURE_SUBSCRIPTION_ID` environment variable to be set, as operations are scoped to a specific subscription. Attempting to initialize clients or perform operations without this variable can lead to errors like `ValueError: Please set the AZURE_SUBSCRIPTION_ID environment variable` or similar messages indicating a missing subscription.
- gotcha Azure Management SDKs typically require the `AZURE_SUBSCRIPTION_ID` environment variable (or passed explicitly) to identify the target subscription for operations. Failure to set this will prevent resource management operations from proceeding.
Install
-
pip install azure-mgmt-servicebus azure-identity
Imports
- ServiceBusManagementClient
from azure.mgmt.servicebus import ServiceBusManagementClient
- DefaultAzureCredential
from azure.common.credentials import ServicePrincipalCredentials
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.servicebus import ServiceBusManagementClient
# Set your Azure Subscription ID and Resource Group in environment variables or replace directly.
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', 'YOUR_SUBSCRIPTION_ID')
resource_group_name = os.environ.get('AZURE_RESOURCE_GROUP_NAME', 'my-servicebus-rg')
namespace_name = os.environ.get('AZURE_SERVICEBUS_NAMESPACE', 'my-servicebus-namespace')
if subscription_id == 'YOUR_SUBSCRIPTION_ID':
raise ValueError("Please set the AZURE_SUBSCRIPTION_ID environment variable.")
# Authenticate using DefaultAzureCredential (looks for env vars, managed identity, etc.)
credential = DefaultAzureCredential()
# Create a Service Bus Management Client
servicebus_client = ServiceBusManagementClient(credential, subscription_id)
try:
# Example: List all Service Bus namespaces in a resource group
print(f"Listing Service Bus namespaces in resource group '{resource_group_name}':")
namespaces = servicebus_client.namespaces.list_by_resource_group(resource_group_name)
for ns in namespaces:
print(f" - {ns.name} (Location: {ns.location}, Status: {ns.status})")
# Example: Get a specific Service Bus namespace (if it exists)
print(f"\nGetting Service Bus namespace '{namespace_name}':")
try:
ns_details = servicebus_client.namespaces.get(resource_group_name, namespace_name)
print(f" Namespace '{ns_details.name}' found. Status: {ns_details.status}")
except Exception as e:
print(f" Namespace '{namespace_name}' not found or error: {e}")
except Exception as e:
print(f"An error occurred: {e}")