Search code examples
azure-bicepbicep

Load json files in Bicep - with dynamic names


Is it possible to load json file in the bicep from a dynamic name ? e.g.

var environment = 'dev'
var mydata = loadJsonContent('../configs/rules_${environment}.json')

I would need to read files with different configurations depending on the environment.

Thank you in advance for all your suggestions and help


Solution

  • Reading files with different configurations depending on the environment using bicep.

    In bicep as per GitHub while using loadJsonContent the file should be known and fixed we cannot vary this input while execution itself. Which was not supports dynamic inputs in the parameters.

    Instead, you can try the following approach by the changing the value of parameter from the deployment command.

    rules_dev.json:

    {
      "ruleName": "DevRule",
      "rulePriority": "High"
    }
    

    same way does for rules.prod.json & now

    Now let's as your requirement is for dev

    main.bicep:

    param environment string = 'dev'
    
    var configData = environment == 'dev' ? loadJsonContent('./rules_dev.json') : loadJsonContent('./rules_prod.json')
    
    resource ruleSet 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
      name: 'vinayRuleSet'
      location: resourceGroup().location
      kind: 'AzureCLI'
      properties: {
        azCliVersion: '2.0.80'
        scriptContent: 'echo "Applying rules..."'
        arguments: '--rule-name ${configData.ruleName} --rule-priority ${configData.rulePriority}'
        retentionInterval: 'P1D'
        timeout: 'PT30M'
      }
    }
    
    output ruleName string = configData.ruleName
    output rulePriority string = configData.rulePriority
    

    Use the command mentioned as below for deployment.

    az deployment group create --resource-group vinay-rg --template-file main.bicep --parameters environment=dev
    

    where you are mentioning the particular environment from the parameter input as per the requirement

    Deployment:

    enter image description here

    for further understanding refer:

    https://github.com/Azure/bicep/issues/413

    https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/parameter-files?tabs=Bicep#parameter-type-formats