listKeys fires too early in the execution graph
- Dominant language
- Bicep
- Stars
- 3.6k
- Forks
- 830
- Avg merge
- 1d 21m
- Merged PRs (30d)
- 79
Description
**Bicep version**
Bicep CLI version 0.7.4 (5afc312467)
**Describe the bug**
When using listKeys as a function, it creates two separate steps in the deployment that are not respecting any dependsOn or naming requirements. These leads to deployments that always fail at first deployment as they try to listKeys from a storage account that is not deployed yet. This also means that on first deployment, the Function Apps are not deployed, as a dependency (the listKeys entries) has failed.

If the same template is deployed again, it works as the storage accounts already exist and the Function Apps are actually created.

It is probably caused by the multiple app settings of the function app that need the storage account key and which are currently implemented like this:
```bicep
...
appSettings: [
{
name: 'AzureWebJobsStorage'
value: 'DefaultEndpointsProtocol=https;AccountName=${functionStorage[index].outputs.name};EndpointSuffix=${environment().suffixes.storage};AccountKey=${listKeys(resourceId(subscription().subscriptionId, format('{0}-{1}', prefix, environment), 'Microsoft.Storage/storageAccounts', substring(format('{0}function{1}{2}', prefix, 'storage', environment), 0, length(format('{0}function{1}{2}', prefix, 'storage', environment)) >= 24 ? 24 : length(format('{0}function{1}{2}', prefix, 'storage', environment)))), '2021-09-01').keys[0].value}'
}
...
]
...
```
There is a lot of duplication of functions, as it is currently not possible to directly reference the `name` or any other property like the `resourceId` of the storage account resource in functions. Instead we have to execute the storage name generation logic every time we need the storage name, which is used in the `resourceId` and `listKeys` functions.
As the storage account also has length limitations which are incorporated into the naming function, they are also checked every time.
**To Reproduce**
I have created a reproduction repository with a minimal deployment of a function app to reproduce the error.
The following resources are deployed (in a loop over how many environments you want)
- Resource group
- storage account for the Function App
- Hosting plan for the Function App
- Function App itself with the `AzureWebJobsStorage` app setting
To recreate the environment, just clone the repository https://github.com/itpropro/bicep-reproduction and execute `az deployment sub create -l 'westeurope' -n (New-Guid).Guid -f .\reproduction.bicep`, no parameters needed.
When you deploy for the first time, it should look like on the above screenshot, when you deploy the same template a second time, there should be no errors.
Contributor guide
Assessment
This issue has not been assessed yet.