Azure IoT Hub - create policy with supplied keys - azure

I'm looking for a way to create access policy in Azure IoT hub but I'd like to supply my own keys.
I can see there is a command in Azure CLI:
az iot hub policy create --hub-name
--name
--permissions
[--resource-group]
[--subscription]
but it does not allow to provide my own keys.
I couldn't find anything interesting on PowerShell as well - seems like there is no command for creating shared access policy at all using PowerShell.
There is a way to use ARM template (seems like it is possible to provide primary and secondary key (https://learn.microsoft.com/en-us/azure/templates/microsoft.devices/iothubs?tabs=json#iothubproperties):
...
"properties": {
"allowedFqdnList": [ "string" ],
"authorizationPolicies": [
{
"keyName": "string",
"primaryKey": "string",
"rights": "string",
"secondaryKey": "string"
}
],
...
but it brings some hassle in terms how to provide the keys and I'm looking for something simple and preety much one-timer.

You can use the below sample arm template which create a basic iot hub & a shared access policy with our own keys. You need to create two files parameters.json & template.json.
template.json file contains the code which resources are going to deploy.
parameters.json file contains the value of those parameters that you have used in the template.json.
Template.json file:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"IotHubs_IotHub_connectionString": {
"type": "SecureString"
},
"IotHubs_IotHub_containerName": {
"type": "SecureString"
},
"IotHubs_IotHub_name": {
"defaultValue": "vedodIotHub",
"type": "String"
},
"IotHubs_Key_Name" : {
"defaultValue" : "newkeyname",
"type": "string"
},
"IotHubs_Key_Primary_value" : {
"type": "string"
},
"IotHubs_Key_Secondary_value":{
"type": "string"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Devices/IotHubs",
"apiVersion": "2021-07-02",
"name": "[parameters('IotHubs_IotHub_name')]",
"location": "eastus",
"sku": {
"name": "S1",
"tier": "Standard",
"capacity": 2
},
"identity": {
"type": "None"
},
"properties": {
"ipFilterRules": [],
"authorizationPolicies": [
{
"keyName": "[parameters('IotHubs_Key_Name')]",
"primaryKey": "[parameters('IotHubs_Key_Primary_value')]",
"secondaryKey" : "[parameters('IotHubs_Key_Secondary_value')]",
"rights": "RegistryRead, RegistryWrite, DeviceConnect"
}
],
"eventHubEndpoints": {
"events": {
"retentionTimeInDays": 1,
"partitionCount": 4
}
},
"routing": {
"endpoints": {
"serviceBusQueues": [],
"serviceBusTopics": [],
"eventHubs": [],
"storageContainers": []
},
"routes": [],
"fallbackRoute": {
"name": "$fallback",
"source": "DeviceMessages",
"condition": "true",
"endpointNames": [
"events"
],
"isEnabled": true
}
},
"storageEndpoints": {
"$default": {
"sasTtlAsIso8601": "PT1H",
"connectionString": "[parameters('IotHubs_IotHub_connectionString')]",
"containerName": "[parameters('IotHubs_IotHub_containerName')]"
}
},
"messagingEndpoints": {
"fileNotifications": {
"lockDurationAsIso8601": "PT1M",
"ttlAsIso8601": "PT1H",
"maxDeliveryCount": 10
}
},
"enableFileUploadNotifications": false,
"cloudToDevice": {
"maxDeliveryCount": 10,
"defaultTtlAsIso8601": "PT1H",
"feedback": {
"lockDurationAsIso8601": "PT1M",
"ttlAsIso8601": "PT1H",
"maxDeliveryCount": 10
}
},
"features": "None"
}
}
]
}
parameters.json file :
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"IotHubs_IotHub_connectionString": {
"value": ""
},
"IotHubs_IotHub_containerName": {
"value": ""
},
"IotHubs_IotHub_name": {
"value": "<IotHubName>"
},
"IotHubs_Key_Name":{
"value" : "<sharedaccesspolicyKeyName>"
},
"IotHubs_Key_Primary_value": {
"value" : "<accesspolicyPrimaryKeyValue>"
},
"IotHubs_Key_Secondary_value":{
"value" : "<accesspolicySecondaryKeyValue>"
}
}
}
Using the below Powershell cmdlets to deploy the create a Iot hub & passing the above template.json & parameters.json file as parameters :
New-AzResourceGroupDeployment -ResourceGroupName <resourcegroupName> -TemplateFile '<pathfortemplate.jsonfile>' -TemplateParameterFile '<Pathforparameters.jsonfile>'
Here is the sample output screenshot for reference:

Related

Deployment Script ARM template in Azure

I am using Deployment Script to run powershell with ARM. It needs user-manged identity with contributor role. I have followed steps in below link but it always gives same error.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/deployment-script-template?tabs=PowerShell
Invalid value for the identities '/subscriptions/<subID>/resourcegroups/<rgname>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity'. The 'UserAssignedIdentities' property keys should only be empty json objects, null or the resource exisiting property.
I have extracted principalId and client Id with below command.
Get-AzUserAssignedIdentity -ResourceGroupName 'rGname'
Below is the template
<pre>
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"name": {
"type": "string",
"defaultValue": "'ds test'"
},
"utcValue": {
"type": "string"
},
"subscriptionId": {
"type": "string",
"defaultValue": ""
}
},
"resources": [
{
"type": "Microsoft.Resources/deploymentScripts",
"apiVersion": "2019-10-01-preview",
"identity": {
"type": "userAssigned",
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {
"ClientId": "value",
"PrincipalId": "value"
}
}
},
"kind": "AzurePowerShell", // or "AzureCLI"
"location": "[resourceGroup().location]",
"name": "runPowerShellInlineWithOutput",
"properties": {
"containerSettings": {
"containerGroupName": "deployscriptrun"
},
"storageAccountSettings": {
"storageAccountName": "allscriptstorage",
"storageAccountKey": "key"
},
"azPowerShellVersion": "3.0", // or "azCliVersion": "2.0.80"
"environmentVariables": [
{
"name": "someSecret",
"secureValue": "if this is really a secret, don't put it here... in plain text..."
}
],
"scriptContent" : "write-host 'hello world'",
"supportingScriptUris": [],
//"timeout": "PT30M",
"cleanupPreference": "OnSuccess",
"retentionInterval": "P1D"
}
}
],
"outputs": {
}
}
</pre>
With
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {}
}
I get below error
{
"code": "DeploymentScriptOperationFailed",
"message": "The client 'id' with object id 'id' does not have authorization to perform action 'Microsoft.Resources/subscriptions/providers/read' over scope '/subscriptions/id' or the scope is invalid. If access was recently granted, please refresh your credentials."
}
according to the article linked it should look like this:
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {}
}

How to create Activity logs diagnostic setting for Azure resources using ARM template

We are referring this documentation here which talks about Creating diagnostic setting in Azure using a Resource Manager template.
We have managed to provision resources with ARM template along with diagnostic setting for resource logs, however snippet in the documentation to enable the activity logs diagnostic setting does not seem to work as the template deployment command (new-azresourcegroupdeployment) returns the Bad request error.
New-AzResourceGroupDeployment : Resource Microsoft.Insights/diagnosticSettings 'test-vnet' failed with message '{
"Code": "BadRequest",
"Message": ""
}'
Here is the template (trimmed some code to avoid noise)
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
...
},
"variables": {
...
},
"resources": [
{
"apiVersion": "2018-08-01",
"type": "Microsoft.Network/virtualNetworks",
"name": "[parameters('virtualNetworkName')]",
"location": "[parameters('resourceLocation')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[parameters('addressPrefix')]"
]
},
"subnets": "[parameters('subnets')]",
"dhcpOptions": {
"dnsServers": "[parameters('dnsServers')]"
}
},
"resources":
[
{
"type": "Microsoft.Insights/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"name": "[variables('diagnosticsSettingsName')]",
"dependsOn": [
"[parameters('virtualNetworkName')]"
],
"location": "global",
"properties":
{
"storageAccountId": "..valid_id_here",
"logs":
[
{
"category": "Administrative",
"enabled": true
},
{
"category": "Security",
"enabled": true
},
{
"category": "ServiceHealth",
"enabled": true
},
{
"category": "ResourceHealth",
"enabled": true
}
]
}
}
]
}
],
"outputs": {
..
}
The documentation here which you are referring for Creating diagnostic settings.
So If you will check the Deployment Methods in this document, it says that you can deploy Resource Manager templates using any valid method including PowerShell and CLI. Diagnostic settings for Activity log must deploy to a subscription using az deployment create for CLI or New-AzDeployment for PowerShell.
Use New-AzDeployment instead of New-AzResourceGroupDeployment to deploy the ARM Template.
Hope this helps!!
This policy works for me, note that it is Subscription level deployment:
{
"properties": {
"displayName": "Deploy diagnostic setting profile for Subscription Activity Logs to Log Analytics workspace",
"description": "Deploys the diagnostic settings for Subscription Activity Logs to stream to a regional Log Analytics workspace when any Subscription which is missing this diagnostic settings is created or updated.",
"mode": "All",
"metadata": {
"version": "1.0.0",
"category": "audit"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
},
"settingsProfileName": {
"type": "String",
"metadata": {
"displayName": "Settings profile name",
"description": "The diagnostic settings profile name"
},
"defaultValue": "setbypolicy_logAnalytics"
},
"logAnalyticsResourceId": {
"type": "String",
"metadata": {
"displayName": "Log Analytics resourceId",
"description": "Set to full Log Analytics workspace resorceId. If this workspace is outside of the scope of the assignment you must manually grant 'Log Analytics Contributor' permissions (or similar) to the policy assignment's principal ID."
}
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Resources/subscriptions"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Insights/diagnosticSettings",
"name": "[parameters('settingsProfileName')]",
"existenceCondition": {
"allOf": [
{
"field": "Microsoft.Insights/diagnosticSettings/workspaceId",
"equals": "[parameters('logAnalyticsResourceId')]"
}
]
},
"deploymentScope": "subscription",
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/749f88d5-cbae-40b8-bcfc-e573ddc772fa",
"/providers/microsoft.authorization/roleDefinitions/92aaf0da-9dab-42b6-94a3-d43ce8d16293"
],
"deployment": {
"location": "westeurope",
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"settingsProfileName": {
"type": "string"
},
"logAnalyticsResourceId": {
"type": "string"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Insights/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"name": "[parameters('settingsProfileName')]",
"properties": {
"workspaceId": "[parameters('logAnalyticsResourceId')]",
"logs": [
{
"category": "Administrative",
"enabled": "true"
},
{
"category": "Alert",
"enabled": "true"
},
{
"category": "Autoscale",
"enabled": "true"
},
{
"category": "Policy",
"enabled": "true"
},
{
"category": "Recommendation",
"enabled": "true"
},
{
"category": "ResourceHealth",
"enabled": "true"
},
{
"category": "Security",
"enabled": "true"
},
{
"category": "ServiceHealth",
"enabled": "true"
}
]
}
}
],
"outputs": {}
},
"parameters": {
"settingsProfileName": {
"value": "[parameters('settingsProfileName')]"
},
"logAnalyticsResourceId": {
"value": "[parameters('logAnalyticsResourceId')]"
}
}
}
}
}
}
}
}
}

Azure ARM Deployment what is the hostingEnvironment?

I'm attempting to deploy to a new resource group containing an existing app service plan in Azure using an ARM script. If I run the deployment through the Azure Portal UI, it is successful. The issue happens when I try to download the template ARM script for the deployment and use that.
I'm attempting to create a Web app and associated application insights instance.
Here is my template.json
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"type": "string"
},
"name": {
"type": "string"
},
"location": {
"type": "string"
},
"hostingEnvironment": {
"type": "string"
},
"hostingPlanName": {
"type": "string"
},
"serverFarmResourceGroup": {
"type": "string"
},
"alwaysOn": {
"type": "bool"
},
"currentStack": {
"type": "string"
}
},
"resources": [
{
"apiVersion": "2018-02-01",
"name": "[parameters('name')]",
"type": "Microsoft.Web/sites",
"location": "[parameters('location')]",
"tags": {},
"dependsOn": [
"microsoft.insights/components/LicensingService-API"
],
"properties": {
"name": "[parameters('name')]",
"siteConfig": {
"appSettings": [
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference('microsoft.insights/components/LicensingService-API', '2015-05-01').InstrumentationKey]"
},
{
"name": "ApplicationInsightsAgent_EXTENSION_VERSION",
"value": "~2"
},
{
"name": "XDT_MicrosoftApplicationInsights_Mode",
"value": "default"
},
{
"name": "DiagnosticServices_EXTENSION_VERSION",
"value": "disabled"
},
{
"name": "APPINSIGHTS_PROFILERFEATURE_VERSION",
"value": "disabled"
},
{
"name": "APPINSIGHTS_SNAPSHOTFEATURE_VERSION",
"value": "disabled"
},
{
"name": "InstrumentationEngine_EXTENSION_VERSION",
"value": "disabled"
},
{
"name": "SnapshotDebugger_EXTENSION_VERSION",
"value": "disabled"
},
{
"name": "XDT_MicrosoftApplicationInsights_BaseExtensions",
"value": "disabled"
}
],
"metadata": [
{
"name": "CURRENT_STACK",
"value": "[parameters('currentStack')]"
}
],
"alwaysOn": "[parameters('alwaysOn')]"
},
"serverFarmId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('serverFarmResourceGroup'), '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
"hostingEnvironment": "[parameters('hostingEnvironment')]",
"clientAffinityEnabled": true
}
},
{
"apiVersion": "2015-05-01",
"name": "LicensingService-API",
"type": "microsoft.insights/components",
"location": "westus2",
"tags": {},
"properties": {
"ApplicationId": "[parameters('name')]",
"Request_Source": "IbizaWebAppExtensionCreate"
}
}
]
}
And my parameters.json
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"value": "REMOVED"
},
"name": {
"value": "LicensingService-API"
},
"location": {
"value": "West US 2"
},
"hostingEnvironment": {
"value": ""
},
"hostingPlanName": {
"value": "LicensingServiceProductionAppServicePlan"
},
"serverFarmResourceGroup": {
"value": "LicensingServicePROD"
},
"alwaysOn": {
"value": true
},
"currentStack": {
"value": "dotnetcore"
}
}
}
There is one particular parameter that I'm having issues with. It is the "hostingEnvironment" parameter. I am unable to determine what should be placed in that field, as the default template provided by Azure leaves this blank. If I enter a value here (LicensingServiceProductionAppServicePlan for example), I get an error on the deployment of the web app that reads:
{
"Code": "NotFound",
"Message": "Cannot find Stamp with name LicensingServiceProductionAppServicePlan.",
"Target": null,
"Details": [
{
"Message": "Cannot find Stamp with name LicensingServiceProductionAppServicePlan."
},
{
"Code": "NotFound"
},
{
"ErrorEntity": {
"ExtendedCode": "51004",
"MessageTemplate": "Cannot find {0} with name {1}.",
"Parameters": [
"Stamp",
"LicensingServiceProductionAppServicePlan"
],
"Code": "NotFound",
"Message": "Cannot find Stamp with name LicensingServiceProductionAppServicePlan."
}
}
],
"Innererror": null
}
If I instead remove the parameter from both the template and the parameters files, as suggested in this answer, I get a BadRequest error that reads:
{
"error": {
"code": "InvalidTemplate",
"message": "Unable to process template language expressions for resource '/subscriptions/REMOVED/resourceGroups/LicensingServicePROD/providers/Microsoft.Web/serverfarms/LicensingServicePROD' at line '151' and column '9'. 'The template parameter 'hostingEnvironment' is not found. Please see https://aka.ms/arm-template/#parameters for usage details.'",
"additionalInfo": [
{
"type": "TemplateViolation",
"info": {
"lineNumber": 151,
"linePosition": 9,
"path": ""
}
}
]
}
}
Likely this is because I can see that the "hostingEnvironment" parameter is used in the template script.
So I'm left wondering why this works when done through the Azure UI but not from the script generated from the UI. My final question that I'm looking to solve is what is the value that should be provided for the "hostingEnvironment" parameter?
First hostingEnvironment is not required. It is required if you have an App Service Environment and you want to deploy the site on it.
You can leave it empty the value or remove it from the template.
See the details from the template reference site Web Site template reference
The solution is to make the following changes:
template.json:
"hostingEnvironment": {
"type": "string",
"defaultValue": ""
},
parameters.json
"hostingEnvironment": {
"value": ""
},

ARM Tempate Fails to Export Keys When Account Name Has a Dash

I have an arm template to deploy a documentdb. If i use a dash in the name the document database deploys, but my output params fail; however if I use no dashes in the name output params succeed.
Given a CosmosDbAccountName of accountnamedev, database deploys and keys / endpoint export just fine.
Given a CosmosDbAccountName of accountname-dev, database deploys, but keys fail to export with:
1:41:56 PM - Resource Microsoft.DocumentDB/databaseAccounts 'accountname-dev' failed with message '{
"code": "NotFound",
"message": "Request url is invalid.\r\nActivityId: c048e914-ccba-4be1-a38f-0d8bb89020bf, Microsoft.Azure.Documents.Common/2.1.0.0"
}'
I've found no real descriptions about this being a problem, so I feel like I'm missing something simple, I'm definitely not an ARM expert.
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"CosmosDbAccountName": {
"type": "string"
},
"CosmosDbConsistencyLevel" : {
"type": "string"
},
"CosmosDbConsistencyPolicyMaxIntervalInSeconds" : {
"type" : "string"
},
"CosmosDbConsistencyPolicyMaxStalenessPrefix" : {
"type" : "string"
},
"Location": {
"type": "string"
}
},
"variables": {
"documentDb" : {
"name" : "[parameters('CosmosDbAccountName')]",
"databaseAccountOfferType" : "Standard",
"consistencyPolicy" : {
"defaultConsistencyLevel": "[parameters('CosmosDbConsistencyLevel')]",
"maxIntervalInSeconds": "[parameters('CosmosDbConsistencyPolicyMaxIntervalInSeconds')]",
"maxStalenessPrefix": "[parameters('CosmosDbConsistencyPolicyMaxStalenessPrefix')]"
}
}
},
"resources": [
{
"type": "Microsoft.DocumentDB/databaseAccounts",
"kind": "GlobalDocumentDB",
"name": "[variables('documentDb').name]",
"apiVersion": "2015-04-08",
"location": "[parameters('Location')]",
"properties": {
"databaseAccountOfferType": "[variables('documentDb').databaseAccountOfferType]",
"consistencyPolicy": "[variables('documentDb').consistencyPolicy]",
"locations":[
{
"locationName": "[parameters('Location')]",
"provisioningState": "Succeeded",
"failoverPriority": 0
}
],
"capabilities":[]
},
"dependsOn": []
}
],
"outputs": {
"endPoint": {
"type": "string",
"value":"[concat('https://', variables('documentDb').name, '.documents.azure.com:443/')]"
},
"primaryKey": {
"type":"string",
"value":"[listKeys(resourceId('Microsoft.DocumentDB/databaseAccounts', variables('documentDb').name), providers('Microsoft.DocumentDB','databaseAccounts').apiVersions[0]).primaryMasterKey]"
},
"instanceName": {
"type":"string",
"value":"variables('documentDb').name"
}
}
}
in this case the error was due to the cosmosdb account not being deployed

Deploying autoscale settings using ARM template that depend on Cloud Service

I'm using ARM template file to deploy two resources:
An Azure Cloud Service (with 4 roles)
Autoscale settings (that include rules for all 4 roles)
If the Cloud Service exists, and the roles are running, then I have no issue in deploying both in parallel, it works successfully with the following template.
The issue occurs when the cloud service is being deployed for the first time.
This is reasonable as the autoscale settings need a targetResourceUri to apply the rules, if that resource does not exist - it is good thing to fail the deployment.
For that, they've invented the dependsOn property, but for some reason I cannot get it to work, the autoscale rules fail to be deployed due the targetResourceUri not exists (the scale rules are being deployed too quickly, before the roles are deployed).
Here's the template:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"serviceName": {
"type": "string"
},
"PackageLink": {
"type": "string"
},
"serviceConfigurationLink": {
"type": "string"
},
"deploymentLabel": {
"type": "string"
},
"autoscaled_resource_name": {
"defaultValue": "autoscale-rules-default",
"type": "string"
},
"metricResourceUri_cpu": {
"type": "string"
},
"autoscale_resourceUri": {
"type": "string"
},
"autoscale_rules_enabled": {
"defaultValue": true,
"type": "bool"
},
"min_instance_count": {
"type": "string"
},
"max_instance_count": {
"type": "string"
},
"default_instance_count_when_metric_unavailable": {
"type": "string"
}
},
"variables": {
"resourceLocation": "[resourcegroup().location]"
},
"resources": [
{
"apiVersion": "2016-04-01",
"type": "Microsoft.ClassicCompute/domainNames",
"name": "[parameters('serviceName')]",
"location": "[variables('resourceLocation')]",
"resources": [
{
"apiVersion": "2016-04-01",
"name": "production",
"type": "deploymentSlots",
"dependsOn": [
"[resourceId('Microsoft.ClassicCompute/domainNames', parameters('serviceName'))]"
],
"properties": {
"packageLink": {
"uri": "[parameters('PackageLink')]"
},
"deploymentLabel": "[parameters('deploymentLabel')]",
"ConfigurationLink": {
"uri": "[parameters('serviceConfigurationLink')]"
},
"deploymentOptions": "StartDeployment"
}
}
]
},
{
"type": "microsoft.insights/autoscalesettings",
"name": "[parameters('autoscaled_resource_name')]",
"apiVersion": "2014-04-01",
"location": "eastus",
"dependsOn": [
"[parameters('serviceName')]"
],
"properties": {
"profiles": [
{
"name": "[parameters('autoscaled_resource_name')]",
"capacity": {
"minimum": "[parameters('min_instance_count')]",
"maximum": "[parameters('max_instance_count')]",
"default": "[parameters('default_instance_count_when_metric_unavailable')]"
},
"rules": [
{
"metricTrigger": {
"metricName": "Percentage CPU",
"metricNamespace": "",
"metricResourceUri": "[parameters('metricResourceUri_cpu')]",
"timeGrain": "PT5M",
"statistic": "Average",
"timeWindow": "PT5M",
"timeAggregation": "Average",
"operator": "GreaterThan",
"threshold": 85
},
"scaleAction": {
"direction": "Increase",
"type": "PercentChangeCount",
"value": "45",
"cooldown": "PT10M"
}
}
]
}
],
"enabled": "[parameters('autoscale_rules_enabled')]",
"name": "[parameters('autoscaled_resource_name')]",
"targetResourceUri": "[parameters('autoscale_resourceUri')]",
"notifications": [
{
"operation": "Scale",
"email": {
"sendToSubscriptionAdministrator": true,
"sendToSubscriptionCoAdministrators": true,
"customEmails": []
}
}
]
}
}
]
}
Here's the powershell log:
VERBOSE: Performing the operation "Creating Deployment" on target "************".
WARNING: The DeploymentDebug setting has been enabled. This can potentially log secrets like passwords used in resource
property or listKeys operations when you retrieve the deployment operations through
Get-AzureRmResourceGroupDeploymentOperation
VERBOSE: 1:00:25 AM - Template is valid.
VERBOSE: 1:00:28 AM - Create template deployment 'azuredeploy-0615-2200'
VERBOSE: 1:00:28 AM - Checking deployment status in 5 seconds
VERBOSE: 1:00:34 AM - Checking deployment status in 10 seconds
VERBOSE: 1:00:44 AM - Resource Microsoft.ClassicCompute/domainNames/deploymentSlots '************/production'
provisioning status is running
New-AzureRmResourceGroupDeployment : 1:00:44 AM - Resource microsoft.insights/autoscalesettings
'autoscale-rules-default' failed with message '{
"code": "TargetResourceNotFound",
"message": "The target resource id '/subscriptions/************/resourceGroups/"************/providers/Microsoft.ClassicCompute/domainNames/"************/slots/Production/roles/WorkerRole' was not found."
}'
At C:\Users\************\Deploy-AzureResourceGroup.ps1:98 char:1
+ New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFil ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureRmResourceGroupDeployment], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDep
loymentCmdlet
VERBOSE: 1:00:44 AM - Resource Microsoft.ClassicCompute/domainNames '************' provisioning status is succeeded
VERBOSE: 1:00:45 AM - Checking deployment status in 15 seconds
VERBOSE: 1:01:00 AM - Checking deployment status in 20 seconds
VERBOSE: 1:01:21 AM - Checking deployment status in 25 seconds
VERBOSE: 1:01:47 AM - Checking deployment status in 30 seconds
It looks like the autoscale rules are being deployed even before there's a confirmation on the successful creation of the cloud service.
Do I have a mistake in my configuration?
The depended resources, in my case autoscalesettings should be depended on the deployment of the cloud service, which is either production or staging - both of them of type: Microsoft.ClassicCompute/domainNames/deploymentSlots.
The important part is this:
"dependsOn": [
"[resourceId('Microsoft.ClassicCompute/domainNames/deploymentSlots', parameters('serviceName'), 'production')]"
]
Here's how I've done:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"deploymentLabel": {
"type": "string"
},
"serviceName": {
"type": "string"
},
"PackageLink": {
"type": "securestring"
},
"serviceConfigurationLink": {
"type": "securestring"
},
"autoscaled_resource_name": {
"type": "string"
},
"metricResourceUri": {
"type": "string"
},
"autoscale_resourceUri": {
"type": "string"
}
},
"variables": {
"resourceLocation": "[resourcegroup().location]"
},
"resources": [
{
"apiVersion": "2016-04-01",
"type": "Microsoft.ClassicCompute/domainNames",
"name": "[parameters('serviceName')]",
"location": "[variables('resourceLocation')]",
"resources": [
{
"apiVersion": "2016-04-01",
"name": "production",
"type": "deploymentSlots",
"dependsOn": [
"[resourceId('Microsoft.ClassicCompute/domainNames', parameters('serviceName'))]"
],
"properties": {
"packageLink": {
"uri": "[parameters('PackageLink')]"
},
"deploymentLabel": "[parameters('deploymentLabel')]",
"ConfigurationLink": {
"uri": "[parameters('serviceConfigurationLink')]"
},
"deploymentOptions": "StartDeployment"
}
}
]
},
{
"type": "microsoft.insights/autoscalesettings",
"name": "[parameters('autoscaled_resource_name')]",
"apiVersion": "2014-04-01",
"location": "eastus",
"dependsOn": [
"[resourceId('Microsoft.ClassicCompute/domainNames/deploymentSlots', parameters('serviceName'), 'production')]"
],
"properties": {
"profiles": [],
"enabled": true,
"name": "[parameters('autoscaled_resource_name')]",
"targetResourceUri": "[parameters('autoscale_resourceUri')]"
}
}
]
}

Resources