In this blog post, I’ll provide a way of replacing multiple values in a string in Azure Bicep. We will first look at the traditional way of doing this, which can be quite tedious and repetitive. Then, we will introduce a more efficient method using a user-defined function.
My use case for this was I had an Azure Workbook that I wanted to parametrise in my Bicep code to allow deployments to multiple environments using the same template. Unfortunately there is no way currently to do multiple string replacements in Bicep so I was left with a manual approach or come up with another way.
The Manual Approach
Traditionally, if you wanted to replace multiple values in a string in Azure Bicep, you would have to call the replace function multiple times, once for each value you wanted to replace. Here’s an example:
var myContent = loadTextContent('../myJson.json')
myContent = myContent.replace('param1', 'value1')
myContent = myContent.replace('param2', 'value2')
myContent = myContent.replace('param3', 'value3')
This method works, but is not very efficient. If you have a large number of values to replace, your code can quickly become cluttered and difficult to maintain.
The Optimised Approach
Now, let’s look at a more efficient way to replace multiple values in a string using a user defined function in Bicep. Here’s the function:
func replaceMultiple(input string, replacements { *: string }) string => reduce(
items(replacements), input, (cur, next) => replace(string(cur), next.key, next.value))
This function, replaceMultiple, takes two parameters: the input string and a dictionary of replacements. It uses the reduce function to iterate over the items in the replacements dictionary, replacing each key in the input string with its corresponding value. Put this function somewhere in your bicep file so it can be used elsewhere in your code.
Here’s how you can use this function to replace multiple values in a string:
var myContent = loadTextContent('../myJson.json')var replacedContent = replaceMultiple(myContent, {
'{param1}': 'value1'
'{param2}': 'value2'
'{param3}': 'value3'
})
In conclusion, while the traditional method of replacing multiple values in a string works, it’s not the most efficient. By using a custom function like replaceMultiple, you can simplify your code and make it more maintainable. Happy coding!

Leave a comment