Search code examples
azureazure-resource-managerazure-sdk-.netazure-iot-hubazure-resource-group

Azure ARM - List keys - How to fetch key value of a specific key?


I have setup an Azure IOThub using Azure resource management template. I need to to get the "shared access policy" - 'iothubowner' 's primarykey value and use it for the setup of another resource downstream.

I am able to fetch all the shared access policies and their respective primary keys as an array / object using the listkeys function in the Azure ARM template json as below

"outputs": {
    "IoT_hub_ownerkey1": {
      "value": "[listkeys(resourceId('Microsoft.Devices/IotHubs',variables('vHubName')),'2016-02-03').value]",
      "type": "array"
    }
  }

which results in

      Name             Type                       Value     
  ===============  =========================  ==========
    ioT_hub_ownerkey1  Array                      [
    {
      "keyName": "iothubowner",
      "primaryKey": "mKAQTt9U5XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "secondaryKey": "DpFgimzXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "rights": "RegistryWrite, ServiceConnect, DeviceConnect"
    },
    {
      "keyName": "service",
      "primaryKey": "hrsK7laMIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "secondaryKey": "omm3RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "rights": "ServiceConnect"
    },
    {
      "keyName": "device",
      "primaryKey": "sfE9QbhLDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "secondaryKey": "v5Oyw3XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      "rights": "DeviceConnect"
    },

.... ]

I need to know how to filter only the primarykey of the "iothubowner" policy ?

i tried this but got error

"IoT_hub_ownerkey2": {
  "value": "[listkeys(resourceId('Microsoft.Devices/IotHubs',variables('vHubName')),'2016-02-03').value.keyName['iothubowner'].primaryKey]",
  "type": "string"
}

Error

    {
      "code": "DeploymentOutputEvaluationFailed",
      "target": "IoT_hub_ownerkey2",
      "message": "The template output 'IoT_hub_ownerkey2' is not valid: Template language expression property 'keyName' has an invalid array index. Please 
see https://aka.ms/arm-template-expressions for usage details.."
    }

Solution

  • Here is what I did to output the primary key for the 'iothubowner' from my ARM template:

    "outputs": {
        "IotHubKey": {
          "type": "string",
          "value": "[listKeys(resourceId('Microsoft.Devices/IotHubs/Iothubkeys', variables('iotHubName'), 'iothubowner'), '2016-02-03').primaryKey]"
        }
      }
    

    Hope it helps :)