如何使用 Azure CLI 管理 Azure 資源群組

Azure 資源群組是保留 Azure 解決方案相關資源的容器。 資源群組可能包含記憶體、虛擬機、應用程式、儀錶板、服務,或幾乎您在 Azure 中處理的任何專案。

Azure 命令列介面 (CLI) 可讓您建立、保存及設定預設的 Azure 資源群組。 CLI 也可讓您在建立資源之後清除資源。

Azure 區域識別

Azure 客戶可以選擇在許多不同的區域中部署資源。 在某些情況下,客戶可以藉由選取提供相同服務的鄰近區域來降低成本。 如果識別附近的區域,訊息會顯示要選取以供未來部署的區域。

在下列範例中 az config ,命令是用來停用區域建議訊息:

az config set core.display_region_identified=no

如需 Azure 區域的詳細資訊,請參閱 為您選擇正確的 Azure 區域。

建立資源群組

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

az group create --name MyResourceGroup --location eastus

資源群組屬於單一位置。 若要查看目前訂用帳戶中支援的所有位置,請執行 az account list-locations 命令:

az account list-locations

若要查看目前訂用帳戶的所有資源群組,請使用 az group list 命令:

az group list --output table

提示

參數 --output 是全局參數,適用於所有命令。 數據表值會以易記的格式呈現輸出。 如需詳細資訊,請參閱 Azure CLI 命令的輸出格式。

當您建立資源時,您會在資源群組中建立資源。 下列範例示範使用 az storage account create 命令所建立的記憶體帳戶:

az storage account create --resource-group MyResourceGroup --name storage134 --location eastus --sku Standard_LRS

若要移除資源群組,請 執行 az group delete 命令:

az group delete --name MyResourceGroup

當您移除資源群組時,您會刪除屬於它的所有資源。 這個動作無法復原。 如果您嘗試本文中的任何命令,請刪除您建立的資源群組,以清除您的帳戶。

設定預設資源群組

您可以針對您從本機 Azure CLI 或 Azure Cloud Shell 執行的所有命令設定預設資源群組。 Azure CLI 會將此設定儲存在組態檔本機。 若要查看目前的組態,請 執行 az config get 命令:

az config get

結果會顯示預設資源群組和其他預設值。 如果您第一次使用 Azure CLI,結果可能是空的。

若要設定 Azure CLI 安裝的預設資源群組,請執行 az config set 命令:

az config set defaults.group=MyResourceGroup

這個指令會設定指定索引鍵的值,在此案例 defaults.group中為 。 如需可用的組態選項,請參閱 Azure CLI 組態

注意

az config set 命令不會驗證您輸入的資源群組是否存在。 命令只會儲存機碼/值組。

執行命令之後,下列兩個命令會提供您相同的結果:

az storage account create --resource-group MyResourceGroup --name storage01  --location eastus --sku Standard_LRS
az storage account create --name storage01 --location eastus --sku Standard_LRS

資源群組屬於訂用帳戶。 如果您的組織有多個訂用帳戶,您必須先設定該訂用帳戶,才能在訂用帳戶中使用資源群組。 如果資源群組的預設值不屬於您目前的訂用帳戶,則會產生錯誤。 如需多個訂用帳戶的詳細資訊,請參閱 使用多個 Azure 訂用帳戶

您不需要重設預設值,即可使用其他資源群組。 請改為指定資源群組:

az group create --name OtherResourceGroup --location eastus
az storage account create --resource-group StorageGroups --name storage03  --location westus --sku Standard_LRS

預設值僅適用於您。 這不會影響其他使用者或您透過 Azure 入口網站 所做的變更。

如果您使用保存的參數值,如本文所述,這些值會優先於組態檔中設定的預設值。

設定資源群組鎖定

身為系統管理員,您可能需要鎖定資源群組,以防止使用者刪除或修改資源群組。 如需詳細資訊,請參閱鎖定資源以防止非預期的變更

在 Azure CLI 中 ,使用 az group lock 命令。 例如, az account lock create 命令可以防止使用者刪除資源群組:

az group lock create --name "Cannot delete resource group" --lock-type CanNotDelete

注意

您必須擁有 contributor 資源群組的許可權,才能建立或變更鎖定。

若要查看資源群組上的目前鎖定,請使用 az group lock list 命令:

az group lock list --output table

清除資源

如果您嘗試本文中的任何命令,您可以使用 az group delete 命令來移除您所建立的任何資源:

az group delete --name MyResourceGroup
az group delete --name OtherResourceGroup
az group delete --name StorageGroups

此命令會一次移除群組及其包含的所有資源。

另請參閱