在本教學課程中,您將了解如何在 Azure 中自動將虛擬機器 (VM) 關機。 Azure VM 的自動關機功能可協助降低成本,在不需要 VM 時關閉 VM,並在需要 VM 時自動重新啟動。
登入 Azure 入口網站。
- 在 Azure 入口網站中,瀏覽至您想要設定自動關機的虛擬機器。
- 在虛擬機器的詳細資料頁面中,選取 [操作] 區段底下的 [自動關機]。
- 在 [自動關機] 設定畫面中,將切換開關轉至 [開啟]。
- 設定您希望虛擬機器關閉的時間。
- 如果您想要在關機前收到通知,請在 [關閉前傳送通知] 選項中選取 [是],並根據您的選擇,在 [電子郵件位址] 或 [Webhook URL] 中提供詳細數據。
- 選取 [儲存],以儲存自動關機設定。
若要使用 Azure CLI 設定單一虛擬機器的自動關機,您可以使用下列指令碼:
# Set the resource group name, VM name, and shutdown time
RESOURCE_GROUP_NAME="myResourceGroup"
VM_NAME="myVM" # Add your VM's name here
SHUTDOWN_TIME="18:00"
# Prompt the user to choose whether to auto-restart or leave the machines off
echo "Do you want to auto-restart the machine? (y/n)"
read RESTART_OPTION
# Set the auto-shutdown and auto-start properties based on the user's choice
if [ "$RESTART_OPTION" == "y" ]; then
AUTO_SHUTDOWN="true"
AUTO_START="true"
else
AUTO_SHUTDOWN="true"
AUTO_START="false"
fi
# Set the auto-shutdown and auto-start properties for the VM
az vm auto-shutdown -g $RESOURCE_GROUP_NAME -n $VM_NAME --time $SHUTDOWN_TIME
if [ "$AUTO_START" == "true" ]; then
az vm restart -g $RESOURCE_GROUP_NAME -n $VM_NAME --no-wait
fi
若要使用 Azure CLI 設定多部虛擬機器的自動關機,您可以使用下列指令碼:
# Set the resource group name and shutdown time
RESOURCE_GROUP_NAME="myResourceGroup"
SHUTDOWN_TIME="18:00"
# Prompt the user to choose whether to auto-restart or leave the machines off
echo "Do you want to auto-restart the machines? (y/n)"
read RESTART_OPTION
# Set the auto-shutdown and auto-start properties based on the user's choice
if [ "$RESTART_OPTION" == "y" ]; then
AUTO_SHUTDOWN="true"
AUTO_START="true"
else
AUTO_SHUTDOWN="true"
AUTO_START="false"
fi
# Loop through all VMs in the resource group and set the auto-shutdown and auto-start properties
for VM_ID in $(az vm list -g $RESOURCE_GROUP_NAME --query "[].id" -o tsv); do
az vm auto-shutdown --ids $VM_ID --time $SHUTDOWN_TIME
az vm restart --ids $VM_ID --no-wait
done
上述指令碼使用 az vm auto-shutdown
和 az vm restart
命令來設定指定資源群組中所有 VM 的 auto-shutdown
和 restart
屬性。
--ids
選項可用來依其識別碼指定 VM,而 --time
和 --auto-start-
啟用選項則分別用來設定自動關機和自動啟動屬性。
這兩個指令碼也會提示選擇是否要自動重新啟動機器,或將其關閉,直到手動重新啟動為止。 此選擇用於設定 VM 的 -auto-shutdown-enabled
屬性。
備註
請記得設定時區以符合您的需求,因為國際標準時間 (UTC) 是時區的預設設定。
清理資源
當您不再需要虛擬機器時,請使用下列步驟刪除虛擬機器:
- 瀏覽至左側的虛擬機器概觀頁面
- 從頂端中間選項中選取 [刪除]。
- 依照提示刪除虛擬機器。
如需如何刪除虛擬機器的詳細資訊,請參閱刪除 VM。
後續步驟
了解 VM 的大小以及如何調整大小: