Azure Template Specs - Part 4 - Bicep Modules

2023, Apr 12

Template Specs can also be referenced on Bicep Modules, using a configuration file, to connect the Module to the Azure Template Spec.

The Configuration file

The configuration file is a json that is used as a module alias, that references the Azure subscription and resource group. Considering the file bicepconfig.json:

File bicepconfig.json

{
  "moduleAliases": {
    "ts": {
      "TemplateSpecs": {
        "subscription": "00000000-0000-0000-0000-000000000000",
        "resourceGroup": "template-specs"
      }
    }
  }
}

Make sure to replace the subscription with the subscriptionId, and resourceGroup which was populated with the same available in Part 1.

The Bicep Module

The alias created on json has a nested structure ts-->TemplateSpecs, and similarly, it should be referenced on the Bicep module:

File /modules/storageModule.bicep

param location string = resourceGroup().location

module stgModule 'ts/TemplateSpecs:Storage:1.0.0' = {
  name: 'storageTSDeploy'
  params: {
    storageAccountType: 'Standard_GRS'
    location: location
  }
}

The example defines a module stgModule that wraps up the Template Spec reference.

This approach should be considered if you have modules organized in a different repository, so rather than copying the module and duplicating it, you can reference it from a central location. In this case the Template Spec.

On main.bicep the module1 is referenced:

File main.bicep

targetScope = 'subscription'

@description('The storage account location.')
param location string

resource templateSpecsTest 'Microsoft.Resources/resourceGroups@2022-09-01' existing = {
  name: 'templateSpecsTest'
}

module stgModule './modules/storageModule.bicep' = {
  name: 'storageDeploy'
  scope: templateSpecsTest
  params: {
    location: location
  }
}

Then we can run the following PowerShell2 or Azure CLI3:

New-AzSubscriptionDeployment -Location australiaeast -TemplateFile ".\main.bicep" -locationFromTemplate 'australiaeast'
az deployment sub create -f .\main.bicep -l australiaeast -p location='australiaeast'

Make sure the resource group templateSpecsTest is created before running any of the commands, as it is hardcoded on main.bicep.

Full Series

Azure Template Specs - Part 1 - Introduction

Azure Template Specs - Part 2 - Scripting

Azure Template Specs - Part 3 - Template Links

Azure Template Specs - Part 4 - Bicep Modules