Methods To Test and Review Your Bicep Code

Testing your Bicep code is important to ensure the integrity and reliability of your infrastructure as code. Combining different testing methods provides a comprehensive validation process. This post will cover various techniques to test and review your Bicep code effectively.

Using Bicep Build with the Bicep CLI

One of the fundamental steps is to use bicep build with the Bicep CLI. This ensures that your Bicep code can be compiled into an ARM template without errors.

az bicep build --file main.bicep

If the build is successfull, there will be no output. You'll receive a json file within the same directory containing the compiled bicep code.

Validating with Azure CLI

A similar validation can be achieved using the az deployment group validate command. This checks for syntax errors in your Bicep code by attempting a deployment validation.

az deployment group validate --resource-group MyResourceGroup --template-file main.bicep

At the end of the output you should see something like this:

"provisioningState": "Succeeded",
    "templateHash": "13530541349148118437",
    "templateLink": null,
    "timestamp": "0001-01-01T00:00:00+00:00",
    "validatedResources": []

If there is anything wrong, you'll receive warning messages like this for example:

/home/runner/work/bicep-modules/bicep-modules/database/cosmosdb-tablesapi/main.bicep(47,42) : Warning outputs-should-not-contain-secrets: Outputs should not contain secrets. Found possible secret: function 'listConnectionStrings' [https://aka.ms/bicep/linter/outputs-should-not-contain-secrets]

Previewing Changes with What-If Operations

To get a preview of the resources that will be deployed or changed, you can use the What-If operation. This is particularly useful for understanding the impact of updates to your code.

az deployment group what-if --resource-group MyResourceGroup --template-file main.bicep

Output:

Testing with PSRule for Azure Well-Architected Framework

The final step is to test your Bicep code against the Azure Well-Architected Framework using PSRule. This helps you ensure that your resources are configured according to best practices.

PSRule - Install
Validate infrastructure as code (IaC) and objects using PowerShell rules.
Invoke-PSRule -InputPath .\main.bicep -Module PSRule.Rules.Azure

You also get a report about the specific resources you want to deploy:

By incorporating these testing methods, you can confidently validate and review your Bicep code, ensuring it meets both functional requirements and best practices. Regular testing helps catch errors early and maintains the quality and security of your deployments.