使用 Azure CLI 來管理 Azure 資源群組

了解如何搭配 Azure Resource Manager 使用 Azure PowerShell 管理您的 Azure 資源群組。 若要管理 Azure 資源,請參閱使用 Azure CLI 管理 Azure 資源

必要條件

什麼是資源群組

「資源群組」是存放 Azure 解決方案相關資源的容器。 該資源群組可包含解決方案的所有資源,或是只包含您想以群組方式管理的資源。 您可決定如何根據對組織最有利的方式,將資源新增至資源群組。 一般而言,將共用相同生命週期的資源新增至相同的資源群組,以便您輕鬆地以群組的形式部署、更新和刪除資源。

資源群組會儲存資源相關中繼資料。 當您指定資源群組的位置時,您便是指定中繼資料的儲存位置。 基於合規性,您可能需要確保資料存放在特定區域中。

建立資源群組

若要建立資源群組,請使用 az group create

az group create --name demoResourceGroup --location westus

列出資源群組

若要列出訂用帳戶中的資源群組,請使用 az group list

az group list

若要取得一個資源群組,請使用 az group show

az group show --name exampleGroup

刪除資源群組

若要刪除資源群組,請使用 az group delete

az group delete --name exampleGroup

如需 Azure Resource Manager 如何決定資源刪除順序的詳細資訊,請參閱 Azure Resource Manager 資源群組刪除

部署資源

您可以使用 Azure CLI 來部署 Azure 資源,或部署 Azure Resource Manager (ARM) 範本或 Bicep 檔案。

使用儲存體作業部署資源

下列範例會建立一個儲存體帳戶。 您提供給儲存體帳戶的名稱在 Azure 中必須是唯一的。

az storage account create --resource-group exampleGroup --name examplestore --location westus --sku Standard_LRS --kind StorageV2

使用 ARM 範本或 Bicep 檔案部署資源

若要部署 ARM 範本或 Bicep 檔,請使用 az deployment group create

az deployment group create --resource-group exampleGroup --template-file storage.bicep

下列範例顯示您要部署的 Bicep 檔案 storage.bicep

@minLength(3)
@maxLength(11)
param storagePrefix string

var uniqueStorageName = concat(storagePrefix, uniqueString(resourceGroup().id))

resource uniqueStorage 'Microsoft.Storage/storageAccounts@2022-09-01' = {
  name: uniqueStorageName
  location: 'eastus'
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
  properties: {
    supportsHttpsTrafficOnly: true
  }
}

如需部署 ARM 範本的詳細資訊,請參閱使用 Resource Manager 範本和 Azure CLI 部署資源

如需部署 Bicep 檔案的詳細資訊,請參閱使用 Bicep 和 Azure CLI 部署資源

鎖定資源群組

鎖定可防止您組織中的其他使用者不小心刪除或修改重要資源。

若要防止資源群組及其資源遭到刪除,請使用 az lock create

az lock create --name LockGroup --lock-type CanNotDelete --resource-group exampleGroup

若要取得資源群組的鎖定,請使用 az lock list

az lock list --resource-group exampleGroup

若要刪除鎖定,請使用 az lock delete

az lock delete --name exampleLock --resource-group exampleGroup

如需詳細資訊,請參閱使用 Azure Resource Manager 來鎖定資源

標記資源群組

您可以將標籤套用至資源群組和資源,以便以邏輯方式組織您的資產。 如需資訊,請參閱使用標籤組織您的 Azure 資源

將資源群組匯出至範本

若要協助建立 ARM 範本,您可以從現有的資源匯出範本。 如需詳細資訊,請參閱使用 Azure CLI 匯出範本

管理對資源群組的存取

若要管理資源群組的存取權,請使用 Azure 角色型存取控制 (Azure RBAC)。 如需詳細資訊,請參閱使用 Azure CLI 新增或移除 Azure 角色指派

下一步