In previous article, we hare seen what is the format of a bicep file. In that article, we also have seen a basic bicep code to deploy a storage account. In this article, we are going to have a look at how conditional logic can be used to decide whether a resource should be created or not.
Scenario
Let’s say, we want to write bicep code for setting up an environment. Let’s say the same bicep file would be used to setup any environment, be it a feature branch environment, dev environment, staging environment or production environment. Here feature branch environment is the term I am using for the environment where the pull requests are deployed.
Let’s say, for feature branch environment some services are not required to be created. Let’s say a storage account is common for dev environment and feature branch environment. So, when a feature branch is getting deployed, we do not want to deploy the storage account. How can this be achieved ?
Introducing Conditional Logic
Bicep language provides an if statement which can be used with module or a resource element. The syntax is, if
keyword followed by a condition, which should evaluate to true
or false
. If the condition evaluates to true, then resource is created. Otherwise the resource creation is skipped.
So, I am using the same bicep from from previous article and adding a condition to the resource which is deploying the storage account.
The script is taking the environment name as parameter and there is an allowed values decorator, which decides which values are allowed for this parameter.
Operators for Conditional Statement
In the code example given above, we have used an inequality operator (!=). Similar to this there are other comparisons. Some of those operators are mentioned below:
- Equality, represented by ==
- Greater Than, represented by >
- Greater than or Equal, represented by >=
- Less Then, represented by <
- Less or Equal, represented by <=
There are also logical operators. Some of the commonly used operators are – logical AND (&&), logical OR (||) and logical negation represented by exclamation mark. Please refer the documentation for the complete list of operators.
I hope you find this information. Let me know your thoughts.