Bicep 中的資源相依性

部署資源時,您必須確認某些資源部署於其他資源之前。 例如,您需要先有邏輯 SQL 伺服器才能部署資料庫。 您可以將某個資源標示為與其他資源相依,以建立此關聯性。 資源部署的順序是以兩種方式來決定:隱含相依性和明確相依性

Azure Resource Manager 會評估資源之間的相依性,並依其相依順序進行部署。 如果資源並未彼此相依,Resource Manager 就會平行部署資源。 您只需要針對部署在相同 Bicep 檔案中的資源定義相依性。

隱含相依性

一個資源宣告參考相同部署中的另一個資源時,就會建立隱含相依性。 在下列範例中,otherResource 會從 exampleDnsZone 取得屬性。 名為 otherResource 的資源會隱含相依於 exampleDnsZone

resource exampleDnsZone 'Microsoft.Network/dnszones@2018-05-01' = {
  name: 'myZone'
  location: 'global'
}

resource otherResource 'Microsoft.Example/examples@2023-05-01' = {
  name: 'exampleResource'
  properties: {
    // get read-only DNS zone property
    nameServers: exampleDnsZone.properties.nameServers
  }
}

巢狀資源在其包含的資源上也有隱含的相依性。

resource myParent 'My.Rp/parentType@2023-05-01' = {
  name: 'myParent'
  location: 'West US'

  // implicit dependency on 'myParent'
  resource myChild 'childType' = {
    name: 'myChild'
  }
}

包含屬性的資源對父資源具有隱含相依性。 這取決於父資源,而不是其任何其他子資源。

下列範例說明儲存體帳戶和檔案服務。 檔案服務對儲存體帳戶具有隱含相依性。

resource storage 'Microsoft.Storage/storageAccounts@2022-09-01' = {
  name: 'examplestorage'
  location: resourceGroup().location
  kind: 'StorageV2'
  sku: {
    name: 'Standard_LRS'
  }
}

resource service 'Microsoft.Storage/storageAccounts/fileServices@2022-09-01' = {
  name: 'default'
  parent: storage
}

當隱含相依性存在時,請勿新增明確相依性

如需關於巢狀資源的詳細資訊,請參閱在 Bicep 中設定子資源的名稱和類型

明確相依性

明確的相依性是使用 dependsOn 屬性來宣告。 屬性接受資源識別碼的陣列,因此您可以指定多個相依性。 您可以使用 :: 運算子來指定巢狀資源相依性。

下列範例顯示名為 otherZone 的 DNS 區域,其相依於名為 dnsZone 的 DNS 區域:

resource dnsZone 'Microsoft.Network/dnszones@2018-05-01' = {
  name: 'demoeZone1'
  location: 'global'
}

resource otherZone 'Microsoft.Network/dnszones@2018-05-01' = {
  name: 'demoZone2'
  location: 'global'
  dependsOn: [
    dnsZone
  ]
}

雖然您可能傾向使用 dependsOn 來對應資源之間的關聯性,但請務必了解您要這麼做的原因。 例如,若要記錄資源互連的方式,dependsOn 並不是適當的方法。 部署之後,資源不會在其屬性中保留部署相依性,因此不會有可讓您看到相依性的命令或作業。 設定不必要的相依性會拖慢部署時間,因為 Azure Resource Manager 無法平行部署這些資源。

即使有時候需要明確相依性,但其需求卻很罕見。 在多數情況下,您可以使用符號名稱來表示資源之間的相依性。 如果您發現自己設定了明確相依性,則應考慮是否有方法可以將其移除。

視覺化相依性

Visual Studio Code 提供視覺化相依性的工具。 在 Visual Studio Code 中開啟 Bicep 檔案,然後選取左上角的 [視覺化檢視] 按鈕。 下列螢幕擷取畫面顯示虛擬機器的相依性。

Screenshot of Visual Studio Code Bicep resource visualizer

下一步

如需部署資源的語法,請參閱 Bicep 中的資源宣告