'ARM FunctionApp listkeys retrieve previous custom key

We've got ARM deployment template which is working fine, the only issue there is, as we're creating FunctionApp and adding custom key to it that will be referenced in API Management to connect API with FunctionApp backend. It looks like, even with dependsOn in backend resource in template referencing to FunctionKeys resource, listkeys() still fetches one from before deployment. Has anyone faced this scenario and is there anything in particular I'm missing? Or is dependsOn thinking that the key has been deployed already, and even tho future deployments update the key, backend isn't actually waiting for the completion of FunctionKeys resource deployment?

Template snippets:

backends

{
  "type": "Microsoft.ApiManagement/service/backends",
  "apiVersion": "2018-01-01",
  "name": "[concat(parameters('apiManagementServiceName'), '/', variables('functionName'))]",
  "dependsOn": [
    "[resourceId('Microsoft.ApiManagement/service', parameters('apiManagementServiceName'))]",
    "[resourceId('Microsoft.Web/sites', variables('functionName'))]",
    "[resourceId('Microsoft.Web/sites/host/functionKeys', variables('functionName'),'default','apimanagement')]"
  ],
  "properties": {
    "url": "[concat('https://', variables('functionName'), '.azurewebsites.net/api')]",
    "protocol": "http",
    "resourceId": "[concat('https://management.azure.com/subscriptions/', subscription().subscriptionId, '/resourceGroups/', resourceGroup().name, '/providers/Microsoft.Web/sites/', variables('functionName'))]",
    "credentials": {
      "header": {
        "x-functions-key": [
          "[listkeys(concat(variables('functionAppId'), '/host/default/'),'2016-08-01').functionKeys.apimanagement]"
        ]
      }
    }
  }
}

functionKeys

{
  "type": "Microsoft.Web/sites/host/functionKeys",
  "apiVersion": "2018-11-01",
  "name": "[concat(variables('functionName'), '/default/apimanagement')]",
  "dependsOn": [
    "[resourceId('Microsoft.Web/sites', variables('functionName'))]"
  ],
  "properties": {
    "name": "apimanagement"
  }
},


Solution 1:[1]

The listKeys call is scheduled too early... In a greenfield scenario the deployment would fail, in brownfield you "get the old key" instead of the new one. It's a "limitation" in the template engine that you can work around. Basically, you need to nest the deployment that uses the listKeys function (i.e. your backend resource). There's a little bit of detail on it here in the Use a Nested Deployment section

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bmoore-msft