Friday, 30 July 2021

Passing Array Parameter to Bicep Scrip via Azure DevOps Pipeline

 Bicep infrastructure as code allows us to pass array parameters and write loop structure of script to deploy multiple resources to Azure. we can define json array as parameter value in an Azure DevOps variable to pass it as an array parameter to Bicep using a pipeline. However, it would be more appropriate to define varible values in much simpler way such as specifying ; separated value set which can be converted into a json string as in Azure pipeline before passing it to Bicep script. An example would be list of database names to create in the same Azure SQL elastic pool.

Let's consider a bicep module used to create multiple databases taking an array of DB names as parameter.

We need to pass array of DB names in the below syntax. You can see below default value defined in main.bicep where the module is used.

Note that there is no comma between array elements when we use json in Bicep. We can define a variable in Azure DevOps as shown below.

Using the Azure CLI task of Azure DevOps we can deploy the resources to Azure with Bicep scripts. We can use the below PowerShell/PowerShell Core script to generate the array parameter json.
$sqldatabaseNames = '$(sqldatabaseNames)' -split ";" | ConvertTo-Json
$sqldatabaseNames = $sqldatabaseNames.ToString() -replace '"',"'"

This will generate a json string as shown below. Note that we have a comma separating the database names, even tough we did not have it in the Bicep default values.

Then we can pass on the parameter a shown below for example. We use --what-if here to see what would happen if the Bicep script is executes.

az deployment sub create --name '$(infraDeployName)'  `
--location eastus --template-file main.bicep `
--parameters rgName='$(rgName)' rgLocation='$(rgLocation)' 
sqlserverName='$(sqlserverName)' sqlserverAdminUser='$(sqlserverAdminUser)' `
sqlserverAdminPwd='$(sqlserverAdminPwd)' `
sqlserverElasticPoolName='$(sqlserverElasticPoolName)' `
sqlserverElasticPoolSKUCapacity=$(sqlserverElasticPoolSKUCapacity) `
sqlserverElasticPoolSKUName='$(sqlserverElasticPoolSKUName)' `
sqlserverElasticPoolSKUTier='$(sqlserverElasticPoolSKUTier)' `
sqlserverElasticPoolMaxBytes=$(sqlserverElasticPoolMaxBytes) `
sqlserverElasticPoolDBMaxCapacity=$(sqlserverElasticPoolDBMaxCapacity) `
sqlserverElasticPoolDBMinCapacity='$(sqlserverElasticPoolDBMinCapacity)' `
sqlserverElasticPoolZoneRedundant=$(sqlserverElasticPoolZoneRedundant) `
sqldatabaseNames=$sqldatabaseNames --what-if

When the plan is executed in Azure DevOps pipeline using Azure CLI task, you would be able to see it would be planning to create two databases estdbX and testdbY.

Once deployment is exected without --what-if using Azure DevOps pipelines the two databases are getting created in Azure.

No comments:

Popular Posts