There is a trick to solving this problem, and we are successfully using it.
Let us see, for example, how the following template returns a value only if the corresponding resource has been deployed.
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "appInsightsLocation": { "type": "string", "defaultValue": "", "allowedValues": [ "", "northeurope", "westeurope" ] } }, "variables": { "appInsightsName": "exampleAppInsights", "planName": "example-plan", "appInsightsEnabled": "[if(greater(length(parameters('appInsightsLocation')), 0), 'true', 'false')]", "appInsightsOrPlanResource": "[if(bool(variables('appInsightsEnabled')), concat('Microsoft.Insights/components/', variables('appInsightsName')), concat('Microsoft.Web/serverFarms/', variables('planName')))]", "appInsightsKeyOrPlanName": "[if(bool(variables('appInsightsEnabled')), 'InstrumentationKey', 'name')]" }, "resources": [ { "comments": "The example service plan", "apiVersion": "2015-08-01", "type": "Microsoft.Web/serverfarms", "location": "[resourceGroup().location]", "name": "[variables('planName')]", "sku": { "name": "B1", "capacity": 1 }, "properties": { "numberOfWorkers": 1, "name": "[variables('planName')]" } }, { "comments": "The application insights instance", "apiVersion": "2014-04-01", "condition": "[bool(variables('appInsightsEnabled'))]", "type": "Microsoft.Insights/components", "location": "[parameters('appInsightsLocation')]", "name": "[variables('appInsightsName')]", "properties": {} } ], "outputs": { "appInsightsKey": { "value": "[if(bool(variables('appInsightsEnabled')), reference(variables('appInsightsOrPlanResource'))[variables('appInsightsKeyOrPlanName')], '')]", "type": "string" } }
The template declares two resources. One application service plan and one instance of the Insights application. An AppInsights instance is deployed only if the location parameter is not an empty string. Thus, the toolkit key of this instance is also returned only if it was created.
For this, we also need a resource that is always present. In our case, this is a service plan. We use this resource to get the link when AppInsights are not deployed. Of course, this can be any azure resource.
The trick happens with the two variables appInsightsOrPlanResource and appInsightsKeyOrPlanName , which we declare. When appInsightsLocation provided, these two variables ultimately reference the instance key that is returned from the output.
If appInsightsLocation not provided, on the other hand, these two variables contain a valid reference to a service plan that is not used, but it is valid. We need to do this because the if function always evaluates both sides. In this case, an empty string is returned from the output.