Omar.Ebrahim
Omar.Ebrahim

Reputation: 874

Retrieve Azure IoT connection string using Python

I have the following code

conn_str = "HostName=my_host.azure-devices.net;DeviceId=MY_DEVICE;SharedAccessKey=MY_KEY"
device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str)
await device_conn.connect()

This works fine, but only because I've manually retrieved this from the IoT hub and pasted it into the code. We are going to have hundreds of these devices, so is there a way to retrieve this connection string programmatically?

It'll be the equivalent of the following

az iot hub device-identity connection-string show --device-id MY_DEVICCE --hub-name MY_HUB --subscription ABCD1234

How do I do this?

Upvotes: 0

Views: 621

Answers (3)

Dominic Betts
Dominic Betts

Reputation: 2331

Other options you could consider include:

Upvotes: 0

neo
neo

Reputation: 66

The device id and key are you give to the each device and you choose where to store/how to load it. The connection string is just a concept for easy to get started but it has no meaning in the actual technical level.

You can use create_from_symmetric_key(symmetric_key, hostname, device_id, **kwargs) to direct pass key, id and hub uri to sdk.

Upvotes: 1

Omar.Ebrahim
Omar.Ebrahim

Reputation: 874

I found it's not possible to retrieve the actual connection string, but a connection string can be built from the device primary key

from azure.iot.hub import IoTHubRegistryManager
from azure.iot.device import IoTHubDeviceClient

# HUB_HOST is YOURHOST.azure-devices.net
# SHARED_ACCESS_KEY is from the registryReadWrite connection string
reg_str = "HostName={0};SharedAccessKeyName=registryReadWrite;SharedAccessKey={1}".format(
        HUB_HOST, SHARED_ACCESS_KEY)

device = IoTHubRegistryManager(reg_str).get_device("MY_DEVICE_ID")
device_key = device.authentication.symmetric_key.primary_key
conn_str = "HostName={0};DeviceId={1};SharedAccessKey={2}".format(
            HUB_HOST, "MY_DEVICE_ID", device_key)

client = IoTHubDeviceClient.create_from_connection_string(
            conn_str)

client.connect()

# Remaining code here...

Upvotes: 0

Related Questions