Saturday 29 May 2021

Azure Infrastructure as Code (IaC) with Bicep - Creating Resources in Resource Group

 We have discussed getting started with Bicep and creating a resource group with Bicep script scoped to a subscription in the post "Azure Infrastructure as Code (IaC) with Bicep - Getting Started with Development". Once a resource group is created we can start deploying resources in the resource group with Bicep. In this post let's explore the strategy we can use to deploy resources to a a resource group created with Bicep.

Let's assume we need to create a storage account in the resource group we have created previously. We have the option of using a module and create a template to create storage accounts. Let's create a new bicep file named storage.bicep. In that file we can paste the below code to define a storage account.

param storageName string
param storageKind string
param storageSKU string

resource stg 'Microsoft.Storage/storageAccounts@2021-02-01' = {
  namestorageName
  locationresourceGroup().location
  kindstorageKind
  sku: {
    namestorageSKU
  }
}

In the above script  we are specifying three parameters for storage name, SKU and kind of storage. We are setting the location with the resource group location.

Now in our main.Bicep file where we have the resource group creation steps defined we can add the storage account creation step by referring the storage.bicep file as a module as shown below.

targetScope='subscription'
param rgName string
param rgLocation string
param storageName string
param storageKind string
param storageSKU string

resource rg 'Microsoft.Resources/resourceGroups@2021-04-01' = {
  namergName
  locationrgLocation
  tags:{
    'tag''bicepdemo'   
  }
}

module storage 'storage.bicep' = {
  name'storagemodule'
  scope:rg

  params:  {
    storageName:storageName
    storageKind:storageKind
    storageSKUstorageSKU
  }
  
}

As you can see in the above script the scope of the main script is set to subscription. Then a new resource group creation step is defined as described in the post "Azure Infrastructure as Code (IaC) with Bicep - Getting Started with Development".  Then reference to the storage.bicep file is added as a module and the required parameters are passed to create the storage account. As the scope of the storage account the resource group is set utilizing the resource group Bicep script block identifier. Once you execute the above main.bicep script with a command similar to below, a resource group would be created if not already exists and a new storage account would be created.

az deployment sub create --location centralus --template-file main.bicep --parameters rgName=rg-bicepdemo02 rgLocation=eastus storageName=stbicepdemo02 storageKind=StorageV2 storageSKU=Standard_LRS



No comments:

Popular Posts