Here is the Python code that retrieves the device connection string:

from azure.mgmt.iothub import IotHubClient
from azure.identity import DefaultAzureCredential
from azure.mgmt.iothub.models import SharedAccessSignatureAuthorizationRule

# Subscription ID and resource group
subscription_id = 'ABCD1234'  # Your subscription ID
resource_group = 'my-resource-group'
iot_hub_name = 'my-iot-hub'
device_id = 'MY_DEVICE'

# Use DefaultAzureCredential for authentication
credential = DefaultAzureCredential()

# Initialize IoT Hub client
iot_hub_client = IotHubClient(credential, subscription_id)

# Retrieve the primary connection string for the device
def get_device_connection_string():
    # Get the device identity
    device = iot_hub_client.iot_hub_resource.get_device(resource_group, iot_hub_name, device_id)

    # Get the IoT Hub keys
    keys = iot_hub_client.iot_hub_resource.list_keys(resource_group, iot_hub_name)

    # Construct connection string
    if keys:
        for key in keys:
            if key.rights == "RegistryWrite":
                connection_string = f"HostName={iot_hub_name}.azure-devices.net;DeviceId={device_id};SharedAccessKey={key.primary_key}"
                return connection_string

# Retrieve connection string for the device
conn_str = get_device_connection_string()

print(f"Connection string for device {device_id}: {conn_str}")

 

Support On Demand!

QA Automation