|
| 1 | +# Azure Bicep - Fail Function |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +The `fail()` function in Bicep allows you to stop deployments with custom error messages when conditions are not met. This is useful for enforcing business rules, validating parameters, and ensuring proper configuration before resources are deployed. |
| 6 | + |
| 7 | +## 📃 Benefits of the Fail Function |
| 8 | + |
| 9 | +✅ **Early Validation**: Catches configuration errors before Azure resources are created. |
| 10 | + |
| 11 | +✅ **Clear Error Messages**: Provides custom, descriptive error messages. |
| 12 | + |
| 13 | +✅ **Enforces Standards**: Ensures naming conventions and business rules are followed consistently. |
| 14 | + |
| 15 | +✅ **Prevents Runtime Issues**: Stops deployments that would fail to function properly. |
| 16 | + |
| 17 | +## Examples |
| 18 | + |
| 19 | +### Storage Account Naming Convention |
| 20 | + |
| 21 | +Ensures storage account names start with "st" prefix. The fail function here is populating the `storageAccountNameChecked` var with our fail condition, if the `storageAccountName` value does not start with the value from `storageAccountPrefix` then it will fail pre-deployment. |
| 22 | + |
| 23 | +```bicep |
| 24 | +var storageAccountPrefix = 'st' |
| 25 | +var storageAccountNameChecked = startsWith(storageAccountName, storageAccountPrefix) |
| 26 | + ? storageAccountName |
| 27 | + : fail('The storage account name must start with "${storageAccountPrefix}".') |
| 28 | +``` |
| 29 | + |
| 30 | +### Web App Runtime Validation |
| 31 | + |
| 32 | +Ensures that the DOTNET runtime stack is specified. In this example, the `fail` function checks whether the `runtime` parameter includes "DOTNET" by using the `contains` function. If "DOTNET" is not found in the `runtime` value, the deployment will be stopped before any resources are created, displaying your custom error message. |
| 33 | + |
| 34 | +```bicep |
| 35 | +var varRuntime = contains(toUpper(runtime), 'DOTNET') ? runtime : fail('The runtime parameter must contain "DOTNET"!') |
| 36 | +``` |
| 37 | + |
| 38 | +## 🚀 Deployment |
| 39 | + |
| 40 | +In Visual Studio Code open a terminal and run: |
| 41 | + |
| 42 | +CLI |
| 43 | + |
| 44 | +```bash |
| 45 | +az login |
| 46 | +az account set --subscription 'subscription name or id' |
| 47 | +az deployment group create -g 'your-rg' --confirm-with-what-if -f './storage.bicep' -p 'storage.bicepparam' |
| 48 | +// amend to webApp.bicep / webApp.bicepparam to test that example |
| 49 | +``` |
| 50 | + |
| 51 | +or PowerShell |
| 52 | + |
| 53 | +```powershell |
| 54 | +Connect-AzAccount |
| 55 | +Set-AzContext -Subscription "subscription name or id" |
| 56 | +New-AzResourceGroupDeployment -Confirm -ResourceGroup "your-rg" -TemplateFile "storage.bicep" -TemplateParameterFile "storage.bicepparam" |
| 57 | +// amend to webApp.bicep / webApp.bicepparam to test that example |
| 58 | +``` |
0 commit comments