Azure IoT Hub Management Client

4.0.0 · active · verified Thu Apr 09

The `azure-mgmt-iothub` library is the Microsoft Azure IoT Hub Management Client Library for Python, enabling programmatic control and management of Azure IoT Hub resources. It allows for creating, updating, deleting, and querying IoT Hubs and their associated entities (like consumer groups and private endpoints). The current version is 4.0.0, and it follows the Azure SDK for Python's release cadence, with updates typically aligned with new Azure service features or platform changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Azure using `DefaultAzureCredential` and list all IoT Hubs within your specified Azure subscription. Ensure your `AZURE_SUBSCRIPTION_ID` environment variable is set. For local development, `DefaultAzureCredential` will also pick up credentials from `az login` (Azure CLI).

import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.iothub import IotHubClient

# Ensure AZURE_SUBSCRIPTION_ID is set in your environment variables
# For local development, also set AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
# or use 'az login' for Azure CLI credential.

subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', 'your-subscription-id') # Replace with your actual subscription ID or ensure env var is set
if not subscription_id or subscription_id == 'your-subscription-id':
    raise ValueError("Please set the AZURE_SUBSCRIPTION_ID environment variable or replace 'your-subscription-id' in the code.")

# Acquire a credential object using DefaultAzureCredential
# This attempts various authentication methods (environment variables, managed identity, CLI, etc.)
credential = DefaultAzureCredential()

# Construct an IoT Hub client
client = IotHubClient(credential, subscription_id)

# Example: List all IoT Hubs in the subscription
print("Listing all IoT Hubs in the subscription...")
iot_hubs = client.iot_hub_resource.list_by_subscription()

found_hubs = False
for hub in iot_hubs:
    found_hubs = True
    print(f"  - Name: {hub.name}, Location: {hub.location}")

if not found_hubs:
    print("No IoT Hubs found in this subscription.")

# Example: Get an IoT Hub (replace with actual resource group and hub name if you have one)
# resource_group_name = os.environ.get('AZURE_RESOURCE_GROUP', 'my-resource-group')
# hub_name = os.environ.get('AZURE_IOT_HUB_NAME', 'my-iothub')
# try:
#     single_hub = client.iot_hub_resource.get(resource_group_name, hub_name)
#     print(f"\nRetrieved single IoT Hub: {single_hub.name} in {single_hub.location}")
# except Exception as e:
#     print(f"\nCould not retrieve IoT Hub {hub_name}: {e}")

view raw JSON →