Bicep Language - Beyond Basics - Modules
Reusability and repeatability are two basics requirements when you want to implement Infrastructure as Code (IaC) practices. You looked at how parameters can be added to Bicep files to make those programs reusable. This is the first step towards modularizing your programs. With the ARM JSON templates, you might have used linked templates that are meant to provide similar functionality. Bicep has support for modularity and helps simplify complex configurations into smaller reusable modules.
In this part of the series of articles on Bicep language, you will learn about modularizing Bicep files. You already have the necessary knowledge, parameterizing Bicep files, to start this learning.
Here is an example from one of the previous parts.
|
|
Add some output to this using what you learned in the previous part about using output in Bicep.
|
|
Now, save this as storageAccount.bicep. Congratulations. You just created a Bicep module! Now, to the important part. How do you consume this in another Bicep file?
Consuming a module
The module
keyword helps in consuming a Bicep module. The syntax for consuming a Bicep module is:
|
|
module-identifier, similar to a resource identifier, will be used to reference the module object in other parts of the Bicep file as needed. The name
property within the module will be used as a name for the nested deployment within the generated ARM template. This property is mandatory. And, then the params
property will be used to supply a list of parameter values to the module.
Here is how you can consume the storageAccount
module you created earlier.
|
|
Save this example as main.bicep. Note that it is not necessary that you always store the module files at the same level as the main Bicep file. You can store all modules in a different folder and use that relative path. For example:
|
|
Also, make sure you use the Unix type path. Bicep does not support Windows backslash for cross-platform compatibility reasons. You can compile the main.bicep using bicep build
. Here is how the generated ARM JSON will look like.
|
|
Module iterations
You can use modules with iterations as well. It is straight forward to do this based on what you learned in the earlier part about iterations in Bicep.
|
|
You can quickly build an example that uses module iteration. Start with a module first. This module will be used to create a virtual network and a subnet within that.
|
|
Save this as vnet.bicep.
To consume this, create a main bicep file.
|
|
The variable vNet
will hold a collection of virtual networks that need to be created. Using the collection iteration along with module declaration, you can supply the necessary parameter values needed for the module parameters.
As you start building complex templates, you will find modules very helpful. This is it for today. You will learn about conditional deployments in the next part of this series.
Share on: