Home Azure Azure – Using the ARM Listkeys() Function to Retrieve Log Analytics WorkSpace Keys

Azure – Using the ARM Listkeys() Function to Retrieve Log Analytics WorkSpace Keys

by admin

If you need to connect your new virtual machine to an Azure OMS Log Analytics Workspace, at the time of deployment, you can do so using the OMS Extension, which can be added to your template using the following code:

{
      "type": "Microsoft.Compute/virtualMachines/extensions",
      "name": "[concat(parameters('vmName'),'/omsextension')]",
      "apiVersion": "2018-04-01",
      "location": "[resourceGroup().location]",
      "dependsOn": [
        "[concat('Microsoft.Compute/virtualMachines/', parameters('vmName'))]"
      ],
      "properties": {
        "publisher": "Microsoft.EnterpriseCloud.Monitoring",
        "type": "MicrosoftMonitoringAgent",
        "typeHandlerVersion": "1.0",
        "autoUpgradeMinorVersion": true,
        "settings": {
          "workspaceId": "[parameters('omsworkspaceid')]"
          },
        "protectedSettings": {
          "workspaceKey": "[parameters('omsworkspacekey')]"
        }
      }
    }

This code works fine, and deploys the Microsoft Monitoring Agent onto the virtual machine, and connects it to the log analytics workspace, based on the workspace ID, supplied using the following parameter:

"workspaceId": "[parameters('omsworkspaceid')]"

It is able to access/authenticate to the log analytics workspace using the omsworkspacekey parameter, listed under the protected settings:

"workspaceKey": "[parameters('omsworkspacekey')]"

The problem with this approach is that you need to provide the OMS key as a parameter when deploying the template. This isn’t the most efficient way as the key would need to be recorded, or retrieved from the OMS workspace settings, in order to populate the parameter when deploying. Luckily the listkeys() function allows for an alternative method. Rather than supplying the workspace key using a parameter, we can have the ARM template retrieve the key programmatically using listkeys(). To do so, we replace the workspace key parameter with the following code:

"workspaceKey": "[listKeys(variables('omsid'), '2015-11-01-preview').primarySharedKey]"

This will allow the ARM template to look up the value of the primary shared key for the workspace, rather than it having to be supplied as a parameter, or written into the template.

Note I’m using a variable called ‘omsid’ which supplies the location of the OMS workspace.

"omsid": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/',parameters('omsrg'), '/providers/','Microsoft.OperationalInsights/workspaces/', parameters('omsworkspace'))]"

For more information on the listkeys() function, have a look here.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More