Tips & Tricks
December 2, 2022
Bicep is a great tool to deploy your infrastructure in Azure but the lack of states like Terraform and the poor results of the “what if” deployment checks make it more challenging to manage the lifecycle of resources modified outside of the code.
This article will provide some tips to help you work around these limitations.
To illustrate the management of child resources, we will deploy a virtual network and its child resources; the subnets!
This Bicep code will deploy a simple virtual network that takes as parameters the name of the virtual network and an array of address prefixes. The virtual network deployed will have a default subnet created for each address prefix that covers the whole range.
We will now run the following GitHub workflow and verify it in Azure:
In this case, we can see a virtual network deployed with the default subnet covering the whole 10.0.0.0/24 address prefix.
Now let's assume that this virtual network is delivered to another team that will change the subnetting to fit their need outside of the Bicep code. For example, they can split the default subnet into two smaller ones for their application's front- and backend.
Now, if we rerun our workflow, Bicep will revert to the default virtual network or even fail if any resources are connected to the subnets.
Bicep allows you to reference existing resources by using the conveniently named keyword “existing.” That keyword enables you to reference a resource that has been created outside of your code. For example, it can be used to import an existing resource in your code to apply changes to it or retrieve some of its configurations to use in your code.
We’ll use it for the latter; to retrieve changes made on resources we manage outside of our code and re-apply it within.
So, let’s modify our code to use the deployed virtual network and inject the modified subnets into our deployment.
There are a couple of caveats with this method.
The first one is that the “existing” keyword will make the deployment fail if the resource doesn’t exist; that’s why the parameter “virtualNetworkExists” has been added to the template together with a condition to the existing resource.
The second caveat is that existing resources can’t be used in a subsequent resource in the same Bicep module. That will generate the following error:
To avoid this issue, we move the actual resource into a sub-module:
Now, to be able to verify if the virtual network indeed exists before deploying our infrastructure, we need to add some PowerShell (or CLI) in our workflow:
There you go! Now you can let other teams modify child resources such as subnets, peering, NSG and route table association, or Key Vault access policies and still maintain the parent resource in your own code.