Search code examples
azureazure-bicepinfrastructure-as-code

Bicep: How do I make one module wait until a second module is ready?


I have a bicep with two modules. The first module creates an Azure SQL server using:

Microsoft.Sql/servers@2022-08-01-preview

The second module creates a database on this Azure SQL Server using:

Microsoft.Sql/servers/databases@2022-08-01-preview

The database creation (second module) fails because the Server (the first module) doesn't exist.

When I run it again, the database is created.

I assume there is some time before the server is ready, and the database creation runs too soon.

I get this error:

The Resource 'Microsoft.Sql/servers/sql-test-d-e2-001/databases/master' under resource group 'rg-testgroup-persist-d-001' was not found

How can I wait until the server is ready? Or is there a better fix for this issue?


Solution

  • Bicep: How do I make one module wait until a second module is ready:-

    The dependsOn property can be used to indicate that the second module is dependent on the first. This ensures that the first module gets created before the second module.

    param  serverName  string = uniqueString('sql',  resourceGroup().id)
    param  sqlDBName  string = 'SampleDB'
    param  location  string = resourceGroup().location
    param  administratorLogin  string = 'newuser'
    @secure()
    param  administratorLoginPassword  string = 'xxxxxx'
    resource  sqlServer  'Microsoft.Sql/servers@2022-05-01-preview' = {
    name: serverName
    location: location
    properties: {
       administratorLogin: administratorLogin
       administratorLoginPassword: administratorLoginPassword
      }
    }
    resource  sqlDB  'Microsoft.Sql/servers/databases@2022-05-01-preview' = {
    parent: sqlServer
    name: sqlDBName
    location: location
    sku: {
       name: 'Basic'
       tier: 'Basic'
    }
    dependsOn: [
        sqlServer
      ]
    }
    

    Refer MSDoc for the sample template.

    az deployment group create --resource-group "Jahnavi" --template-file sql.bicep
    

    enter image description here

    enter image description here