Create an IoT hub using Azure Resource Manager template (.NET)

You can use Azure Resource Manager to create and manage Azure IoT hubs programmatically. This tutorial shows you how to use an Azure Resource Manager template to create an IoT hub from a C# program.


Azure has two different deployment models for creating and working with resources: Azure Resource Manager and classic. This article covers using the Azure Resource Manager deployment model.


This article has been updated to use the Azure Az PowerShell module. The Az PowerShell module is the recommended PowerShell module for interacting with Azure. To get started with the Az PowerShell module, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

To complete this tutorial, you need the following:

Prepare to authenticate Azure Resource Manager requests

You must authenticate all the operations that you perform on resources using the Azure Resource Manager with Azure Active Directory (AD). The easiest way to configure this is to use PowerShell or Azure CLI.

Install the Azure PowerShell cmdlets before you continue.

The following steps show how to set up password authentication for an AD application using PowerShell. You can run these commands in a standard PowerShell session.

  1. Sign in to your Azure subscription using the following command:

  2. If you have multiple Azure subscriptions, signing in to Azure grants you access to all the Azure subscriptions associated with your credentials. Use the following command to list the Azure subscriptions available for you to use:


    Use the following command to select subscription that you want to use to run the commands to manage your IoT hub. You can use either the subscription name or ID from the output of the previous command:

    Select-AzSubscription `
        -SubscriptionName "{your subscription name}"
  3. Make a note of your TenantId and SubscriptionId. You need them later.

  4. Create a new Azure Active Directory application using the following command, replacing the place holders:

    • {Display name}: a display name for your application such as MySampleApp

    • {Home page URL}: the URL of the home page of your app such as http://mysampleapp/home. This URL does not need to point to a real application.

    • {Application identifier}: A unique identifier such as http://mysampleapp. This URL does not need to point to a real application.

    • {Password}: A password that you use to authenticate with your app.

      $SecurePassword=ConvertTo-SecureString {password} –asplaintext –force
      New-AzADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password $SecurePassword
  5. Make a note of the ApplicationId of the application you created. You need this later.

  6. Create a new service principal using the following command, replacing {MyApplicationId} with the ApplicationId from the previous step:

    New-AzADServicePrincipal -ApplicationId {MyApplicationId}
  7. Set up a role assignment using the following command, replacing {MyApplicationId} with your ApplicationId.

    New-AzRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}

You have now finished creating the Azure AD application that enables you to authenticate from your custom C# application. You need the following values later in this tutorial:

  • TenantId
  • SubscriptionId
  • ApplicationId
  • Password

Prepare your Visual Studio project

  1. In Visual Studio, create a Visual C# Windows Classic Desktop project using the Console App (.NET Framework) project template. Name the project CreateIoTHub.

  2. In Solution Explorer, right-click on your project and then click Manage NuGet Packages.

  3. In NuGet Package Manager, check Include prerelease, and on the Browse page search for Microsoft.Azure.Management.ResourceManager. Select the package, click Install, in Review Changes click OK, then click I Accept to accept the licenses.

  4. In NuGet Package Manager, search for Microsoft.IdentityModel.Clients.ActiveDirectory. Click Install, in Review Changes click OK, then click I Accept to accept the license.

  5. In Program.cs, replace the existing using statements with the following code:

    using System;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Azure.Management.ResourceManager.Models;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.Rest;
  6. In Program.cs, add the following static variables replacing the placeholder values. You made a note of ApplicationId, SubscriptionId, TenantId, and Password earlier in this tutorial. Your Azure Storage account name is the name of the Azure Storage account where you store your Azure Resource Manager template files. Resource group name is the name of the resource group you use when you create the IoT hub. The name can be a pre-existing or new resource group. Deployment name is a name for the deployment, such as Deployment_01.

    static string applicationId = "{Your ApplicationId}";
    static string subscriptionId = "{Your SubscriptionId}";
    static string tenantId = "{Your TenantId}";
    static string password = "{Your application Password}";
    static string storageAddress = "https://{Your storage account name}";
    static string rgName = "{Resource group name}";
    static string deploymentName = "{Deployment name}";

Obtain an Azure Resource Manager token

Azure Active Directory must authenticate all the tasks that you perform on resources using the Azure Resource Manager. The example shown here uses password authentication, for other approaches see Authenticating Azure Resource Manager requests.

  1. Add the following code to the Main method in Program.cs to retrieve a token from Azure AD using the application id and password.

    var authContext = new AuthenticationContext(string.Format  
      ("{0}", tenantId));
    var credential = new ClientCredential(applicationId, password);
    AuthenticationResult token = authContext.AcquireTokenAsync
      ("", credential).Result;
    if (token == null)
      Console.WriteLine("Failed to obtain the token");
  2. Create a ResourceManagementClient object that uses the token by adding the following code to the end of the Main method:

    var creds = new TokenCredentials(token.AccessToken);
    var client = new ResourceManagementClient(creds);
    client.SubscriptionId = subscriptionId;
  3. Create, or obtain a reference to, the resource group you are using:

    var rgResponse = client.ResourceGroups.CreateOrUpdate(rgName,
        new ResourceGroup("East US"));
    if (rgResponse.Properties.ProvisioningState != "Succeeded")
      Console.WriteLine("Problem creating resource group");

Submit a template to create an IoT hub

Use a JSON template and parameter file to create an IoT hub in your resource group. You can also use an Azure Resource Manager template to make changes to an existing IoT hub.

  1. In Solution Explorer, right-click on your project, click Add, and then click New Item. Add a JSON file called template.json to your project.

  2. To add a standard IoT hub to the East US region, replace the contents of template.json with the following resource definition. For the current list of regions that support IoT Hub see Azure Status:

      "$schema": "",
      "contentVersion": "",
      "parameters": {
        "hubName": {
          "type": "string"
      "resources": [
        "apiVersion": "2016-02-03",
        "type": "Microsoft.Devices/IotHubs",
        "name": "[parameters('hubName')]",
        "location": "East US",
        "sku": {
          "name": "S1",
          "tier": "Standard",
          "capacity": 1
        "properties": {
          "location": "East US"
      "outputs": {
        "hubKeys": {
          "value": "[listKeys(resourceId('Microsoft.Devices/IotHubs', parameters('hubName')), '2016-02-03')]",
          "type": "object"
  3. In Solution Explorer, right-click on your project, click Add, and then click New Item. Add a JSON file called parameters.json to your project.

  4. Replace the contents of parameters.json with the following parameter information that sets a name for the new IoT hub such as {your initials}mynewiothub. The IoT hub name must be globally unique so it should include your name or initials:

      "$schema": "",
      "contentVersion": "",
      "parameters": {
        "hubName": { "value": "mynewiothub" }


    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

  5. In Server Explorer, connect to your Azure subscription, and in your Azure Storage account create a container called templates. In the Properties panel, set the Public Read Access permissions for the templates container to Blob.

  6. In Server Explorer, right-click on the templates container and then click View Blob Container. Click the Upload Blob button, select the two files, parameters.json and templates.json, and then click Open to upload the JSON files to the templates container. The URLs of the blobs containing the JSON data are:

    https://{Your storage account name}
    https://{Your storage account name}
  7. Add the following method to Program.cs:

    static void CreateIoTHub(ResourceManagementClient client)
  8. Add the following code to the CreateIoTHub method to submit the template and parameter files to the Azure Resource Manager:

    var createResponse = client.Deployments.CreateOrUpdate(
        new Deployment()
          Properties = new DeploymentProperties
            Mode = DeploymentMode.Incremental,
            TemplateLink = new TemplateLink
              Uri = storageAddress + "/templates/template.json"
            ParametersLink = new ParametersLink
              Uri = storageAddress + "/templates/parameters.json"
  9. Add the following code to the CreateIoTHub method that displays the status and the keys for the new IoT hub:

    string state = createResponse.Properties.ProvisioningState;
    Console.WriteLine("Deployment state: {0}", state);
    if (state != "Succeeded")
      Console.WriteLine("Failed to create iothub");

Complete and run the application

You can now complete the application by calling the CreateIoTHub method before you build and run it.

  1. Add the following code to the end of the Main method:

  2. Click Build and then Build Solution. Correct any errors.

  3. Click Debug and then Start Debugging to run the application. It may take several minutes for the deployment to run.

  4. To verify your application added the new IoT hub, visit the Azure portal and view your list of resources. Alternatively, use the Get-AzResource PowerShell cmdlet.


This example application adds an S1 Standard IoT Hub for which you are billed. You can delete the IoT hub through the Azure portal or by using the Remove-AzResource PowerShell cmdlet when you are finished.

Next steps

Now you have deployed an IoT hub using an Azure Resource Manager template with a C# program, you may want to explore further:

To learn more about developing for IoT Hub, see the following articles:

To further explore the capabilities of IoT Hub, see: