Azure Template Specs - Part 2 - Scripting

2023, Apr 02

Last time we explored Azure Template Specs from the user interface, today let's check the PowerShell commandlets that will allow you to automate provisioning.

The bicep template

Bicep templates are becoming very popular1, so let's use a template for a Storage Account. Same as on Part 1, this is a sample of an Azure Storage V22 which accepts 3 parameters storageAccountType, location and storageAccountName. All of the parameters have default values:

File: storage.bicep

@allowed([
  'Premium_LRS'
  'Premium_ZRS'
  'Standard_GRS'
  'Standard_GZRS'
  'Standard_LRS'
  'Standard_RAGRS'
  'Standard_RAGZRS'
  'Standard_ZRS'
])
@description('Storage Account type.')
param storageAccountType string = 'Standard_LRS'

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

param storageAccountName string = 'store${uniqueString(resourceGroup().id)}'

resource storageAccount 'Microsoft.Storage/storageAccounts@2022-09-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: storageAccountType
  }
  kind: 'StorageV2'
  properties: {}
}

output storageAccountNameOutput string = storageAccount.name

Create a Template Spec via scripting

Assuming we already have a Resource Group template-specs, available in Part 1, then we can run the following PowerShell3 or Azure CLI4:

New-AzTemplateSpec -Name Storage -Version "1.0.0" -ResourceGroupName template-specs -Location australiaeast -TemplateFile "C:\templates\storage.bicep"
az ts create --name Storage --version "1.0.0" --resource-group template-specs --location australiaeast --template-file "C:\templates\storage.bicep"

Provisioning is straightforward. The resource is created on Resource Group.

Create a resource from a Template Spec via scripting

To be able to create any resource from the template spec, we need to retrieve the Template Spec Id:

$id = (Get-AzTemplateSpec -ResourceGroupName template-specs -Name Storage -Version "1.0.0").Versions.Id

Then we can use it to provision the resource we need. Let's change a default parameter as well:

New-AzResourceGroupDeployment -TemplateSpecId $id -ResourceGroupName anyResourceGroup -storageAccountType Standard_GRS

Azure Template Specs can help you to streamline your infrastructure management process, reduce errors, and improve collaboration among teams. Reusable components make IaC modular, organizing infrastructure as a software implementation.

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