Share via


使用 Bicep 建立資源群組

您可以使用 Bicep 來建立新的資源群組。 本文說明如何在部署至訂用帳戶或其他資源群組時建立資源群組。

定義資源群組

若要使用 Bicep 建立資源群組,請以資源群組的名稱和位置定義 Microsoft.Resources/resourceGroups 資源。

下列範例顯示建立空資源群組的 Bicep 檔案。 請注意,其目標範圍是 subscription

targetScope='subscription'

param resourceGroupName string
param resourceGroupLocation string

resource newRG 'Microsoft.Resources/resourceGroups@2022-09-01' = {
  name: resourceGroupName
  location: resourceGroupLocation
}

若要將 Bicep 檔案部署至訂用帳戶,請使用訂用帳戶層級的部署命令。

針對 Azure CLI,請使用 az deployment sub create

az deployment sub create \
  --name demoSubDeployment \
  --location centralus \
  --template-file resourceGroup.bicep \
  --parameters resourceGroupName=demoResourceGroup resourceGroupLocation=centralus

對於 PowerShell 部署命令,請使用 New-AzDeployment 或其別名 New-AzSubscriptionDeployment

New-AzSubscriptionDeployment `
  -Name demoSubDeployment `
  -Location centralus `
  -TemplateFile resourceGroup.bicep `
  -resourceGroupName demoResourceGroup `
  -resourceGroupLocation centralus

建立資源群組和資源

若要建立資源群組並部署資源,請新增模組,以定義要部署至資源群組的資源。 將模組的範圍設為您建立的資源群組所用的符號名稱。 您最多可以部署 800 個資源群組。

下列範例顯示 Bicep 檔案,該檔案會建立資源群組,並將儲存體帳戶部署至該資源群組。 請注意,模組的 scope 屬性設為 newRG,也就是要建立的資源群組所用的符號名稱。

targetScope='subscription'

param resourceGroupName string
param resourceGroupLocation string
param storageName string
param storageLocation string

resource newRG 'Microsoft.Resources/resourceGroups@2022-09-01' = {
  name: resourceGroupName
  location: resourceGroupLocation
}

module storageAcct 'storage.bicep' = {
  name: 'storageModule'
  scope: newRG
  params: {
    storageLocation: storageLocation
    storageName: storageName
  }
}

此模組會使用名為 storage.bicep 的 Bicep 檔案,其中包括下列內容:

param storageLocation string
param storageName string

resource storageAcct 'Microsoft.Storage/storageAccounts@2022-09-01' = {
  name: storageName
  location: storageLocation
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'Storage'
  properties: {}
}

在資源群組部署期間建立資源群組

您也可以在資源群組層級部署期間,建立資源群組。 在該情節中,您會部署至現有的資源群組,並切換至訂用帳戶層級以建立資源群組。 下列 Bicep 檔案會在指定訂用帳戶中建立新的資源群組。 建立資源群組的模組與建立資源群組的範例相同。

param secondResourceGroup string
param secondSubscriptionID string = ''
param secondLocation string

// module deployed at subscription level
module newRG 'resourceGroup.bicep' = {
  name: 'newResourceGroup'
  scope: subscription(secondSubscriptionID)
  params: {
    resourceGroupName: secondResourceGroup
    resourceGroupLocation: secondLocation
  }
}

若要部署至資源群組,請使用資源群組部署命令。

若為 Azure CLI,請使用 az deployment group create

az deployment group create \
  --name demoRGDeployment \
  --resource-group ExampleGroup \
  --template-file main.bicep \
  --parameters secondResourceGroup=newRG secondSubscriptionID={sub-id} secondLocation=westus

若為 PowerShell 部署命令,請使用 New-AzResourceGroupDeployment

New-AzResourceGroupDeployment `
  -Name demoRGDeployment `
  -ResourceGroupName ExampleGroup `
  -TemplateFile main.bicep `
  -secondResourceGroup newRG `
  -secondSubscriptionID {sub-id} `
  -secondLocation westus

下一步

若要了解其他範圍,請參閱: