Package: azure-iot-deviceprovisioning
Azure IoT Device Provisioning client library for PythonThe IoT Hub Device Provisioning Service (DPS) is a helper service for IoT Hub that enables zero-touch, just-in-time provisioning to the right IoT hub without requiring human intervention, allowing customers to provision millions of devices in a secure and scalable manner.This service SDK provides data plane operations for backend apps. You can use this service SDK to create and manage individual enrollments and enrollment groups, and to query and manage device registration records.Learn how to provision devices to your IoT hub(s) with ourquickstarts, tutorials, and samples.Getting startedPrerequisitesPython 3.7 or later is required to use this package. For more details, please read our page onAzure SDK for Python version support policy.You must have anAzure subscriptionand anAzure IoT Hub Device Provisioning Serviceto use this package.This package has been tested with Python 3.7+.
For a more complete view of Azure libraries, see theazure sdk python release.Install the packageInstall the Azure IoT Device Provisioning client library for Python withpip:pipinstallazure-iot-deviceprovisioningCreate an IoT Hub Device Provisioning ServiceIf you wish to create a new Device Provisioning Service, you can use theAzure CLI:# Create a new resource group (if necessary)azgroupcreate--namemy-resource-group--locationwestus2# Create the DPS instanceaziotdpscreate--namemy-dps--resource-groupmy-resource-group--locationwestus2Azure Portal,
orBicep,Create the clientThe Azure IoT Device Provisioning client library for Python allows you to interact with three main operational categories: individual enrollments, enrollment groups, and device registration states.Interaction with these resources starts with an instance of a DeviceProvisioningClient. To create the DeviceProvisioningClient object, you will need the DPS resource's endpoint URL and a credential that allows you to access the resource.Creating the client from Azure credentialsTo use anAzure Active Directory (AAD) token credential,
provide an instance of the desired credential type obtained from theazure-identitylibrary.
For example,DefaultAzureCredentialcan be used to authenticate the client.fromazure.iot.deviceprovisioningimportDeviceProvisioningClientfromazure.identityimportDefaultAzureCredential# Initialize credential objectcredential=DefaultAzureCredential()# Create client using endpoint and credentialclient=DeviceProvisioningClient(endpoint="https://my-dps.azure-device-provisioning.net/",credential=credential)Using a DPS connection string:Depending on your use case and authorization method, you may prefer to initialize a client instance with a DPS
connection string instead of providing the endpoint URL and credential separately. To do this, pass the DPS
connection string to the client'sfrom_connection_stringclass method:fromazure.iot.deviceprovisioningimportDeviceProvisioningClientconnection_string="Hostname=https;SharedAccessKeyName=xxxx;SharedAccessKey=xxxx"client=DeviceProvisioningClient.from_connection_string(connection_string=connection_string)Using SAS CredentialsA client instance can also be initialized with anAzureNamedKeyCredentialusing individual components of a DPS resource's Shared Access Policy, as well as anAzureSasCredentialusing a SAS token generated from the policy components and the DPS endpoint string.fromazure.iot.deviceprovisioningimportDeviceProvisioningClientfromazure.iot.deviceprovisioningimportgenerate_sas_tokenfromazure.core.credentialsimportAzureNamedKeyCredential,AzureSasCredentialdps_endpoint="https://my-dps.azure-device-provisioning.net/"policy_name="<access_policy_name>"policy_key="<access_policy_primary_key>"# AzureNamedKeyCredentialcredential=AzureNamedKeyCredential(name=policy_name,key=policy_key)# AzureSasCredentialsas_token=generate_sas_token(dps_endpoint,policy_name,policy_key)credential=AzureSasCredential(signature=sas_token)client=DeviceProvisioningClient(endpoint=dps_endpoint,credential=credential)Async ClientsThis library includes a complete async API supported on Python 3.5+. To use it, you must
first install an async transport, such asaiohttp.
Seeazure-core documentationfor more information.Key conceptsThe following operation groups comprise the Service data plane layer:Individual enrollmentsEnrollment groupsDevice registrationThe Azure IoT Device Provisioning client library for Python allows you to interact with each of these components through different operation namespaces on the DeviceProvisioningClient.ExamplesThe following sections provide several code snippets covering some of the most common DPS service, including:Create an individual device enrollmentCreate an enrollment with reprovisioning policiesCreate an intermediate x509 certificate enrollment groupCreate an x509 CA certificate enrollment groupCheck device registration statusCreate an individual device enrollmentCreate a symmetric key enrollment to provision an individual device and configure its initial state.fromazure.iot.deviceprovisioningimportDeviceProvisioningClient# Initialize clientclient=DeviceProvisioningClient.from_connection_string(connection_string="<connection_string>")# Construct initial twin with desired properties of {"key": "value"} and a tag of {"env": "Development"}initial_twin={"properties":{"desired":{"key":"value"}},"tags":{"env":"Development"}}# Create a symmetric key individual enrollment with initial twinclient.individual_enrollment.create_or_update(id="<enrollment_id>",enrollment={"registrationId":"<enrollment_id>","attestation":{"type":"symmetricKey",},"deviceId":"<device_id>","initialTwin":initial_twin})Create an enrollment with reprovisioning policiesCreate an individual enrollment with a specific reprovisioning policy.fromazure.iot.deviceprovisioningimportDeviceProvisioningClient# Initialize clientclient=DeviceProvisioningClient.from_connection_string(connection_string="<connection_string>")# Create a reprovisioning policy to migrate the device's data and reassess hub assignmentreprovision_policy={"migrateDeviceData":True,"updateHubAssignment":True}# Create a symmetric key individual enrollment with reprovisioning policyclient.individual_enrollment.create_or_update(id="<enrollment_id>",enrollment={"registrationId":"<enrollment_id>","attestation":{"type":"symmetricKey",},"deviceId":"<device_id>","reprovisionPolicy":reprovision_policy})Create an intermediate x509 certificate enrollment groupCreate an x509 enrollment group to provision one or more devices using x509 attestation.fromazure.iot.deviceprovisioningimportDeviceProvisioningClient# Initialize clientclient=DeviceProvisioningClient.from_connection_string(connection_string="<connection_string>")# Load certificate contentscertificate=open("certificate.pem","rt",encoding="utf-8")cert_contents=certificate.read()# Create x509 enrollment group with an intermediate certclient.enrollment_groups.create_or_update(id="<enrollment_group_id>",enrollment_group={"enrollmentGroupId":"<enrollment_group_id>","attestation":{"type":"x509","x509":{"signingCertificates":{"primary":{"certificate":f"{cert_contents}"},"secondary":{"certificate":f"{cert_contents}"},}},},})Create an x509 CA certificate enrollment groupCreate an enrollment group with an x509 CA certificate attestation.
This will ensure a registered device's certificate chain has been signed by the target CA cert at the control plane layer.fromazure.iot.deviceprovisioningimportDeviceProvisioningClient# Initialize clientclient=DeviceProvisioningClient.from_connection_string(connection_string="<connection_string>")# Load certificate contentsca_certificate=open("ca_certificate.pem","rt",encoding="utf-8")ca_contents=certificate.read()# Create x509 enrollment group with CA Referencesclient.enrollment_groups.create_or_update(id="<enrollment_group_id>",enrollment_group={"enrollmentGroupId":"<enrollment_group_id>","attestation":{"type":"x509","x509":{"caReferences":{"primary":f"{ca_contents}","secondary":f"{ca_contents}",}},},})Check device registration statusfromazure.iot.deviceprovisioningserviceimportDeviceProvisioningClient# Initialize clientclient=DeviceProvisioningClient.from_connection_string(connection_string="<connection_string>")# Query device registrations for an enrollment groupdevice_registrations=client.device_registration_state.query(id="<enrollment_group_id>")# Get device registration status for a particular devicestate=client.device_registration_state.get(id="<device_id>")TroubleshootingConnection String errorsIf you see an error message that statesIoT DPS connection string has missing property: [property], it indicates that your connection string is not formed correctly.Please ensure your connection string is semicolon-delimited, and contains the following properties:hostname,sharedaccesskeyname, andsharedaccesskey.Standard HTTPResponse errorsThe client methods in this SDK raise anHttpResponseErroron request failure.
The HttpResponseError raised by the Azure IoT Hub Device Provisioning client library includes detailed error response information that provides useful insights into what went wrong and includes corrective actions to fix common issues.This error information can be found inside themessageproperty of theHttpResponseErrorinstance.Here is an example of how to catch and handle these errors:try:client.individual_enrollment.create_or_update(id="<enrollment_id>",enrollment={"registrationId":"<enrollment_id>","attestation":{"type":"symmetricKey",},})exceptHttpResponseErroraserror:# handle the error hereiferror.status_code==409:passHTTP 400errors indicate a malformed or bad request. Verify that your inputs are of the correct type and that you have provided all required properties.HTTP 401errors indicate problems authenticating. Check the exception message or logs for more information.HTTP 403errors indicate that the provided user credentials are not authorized to perform a specific operation on this Device Provisioning Service resource.
This can also occur if you have incorrectly generated a SAS credential. Verify your credentials and ensure access to your DPS resource.HTTP 409errors indicate a resource conflict. This can occur if:You are trying to create an object that already existsYou are updating an object using acreate_or_update_method without providing aneTag/if-matchvalueNext stepsMore sample codeGet started with oursamples.
prov
Several samples, as well as async samples, are available to you in the samples directory.Device Registration States(async version):Create a basic enrollment groupRegister a device (Requires device SDK)Query device registration states for an enrollment groupGet device registration stateDelete device registration stateEnrollment Groups(async version):Create a symmetric key enrollment groupCreate an x509 certificate enrollment groupGet an enrollment groupUpdate an enrollment groupGet enrollment group attestation mechanismBulk enrollment group operationsDelete enrollment groupIndividual Enrollments(async version):Create a symmetric key individual enrollmentCreate a TPM attestation individual enrollmentCreate an x509 certificate individual enrollmentGet an individual enrollmentUpdate an individual enrollmentGet an individual enrollment's attestation mechanismBulk individual enrollment operationsDelete an individual enrollmentAdditional documentationFor more extensive documentation on Azure IoT Hub Device Provisioning Service, see theAzure IoT Hub Device Provisioning Service documentationon learn.microsoft.com.ContributingThis project welcomes contributions and suggestions.  Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.Release History1.0.0b1 (2023-06-14)Initial Release