本教程介绍如何自动关闭 Azure 中的虚拟机 (VM)。 Azure 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
选项用于通过 ID 指定虚拟机,--time
和 --auto-start-
选项分别用于设置自动关闭和自动启动属性。
这两个脚本还会提示你选择是自动重新启动计算机还是将其关闭直至手动重新启动。 该选项用于设置 VM 的 --auto-shutdown-enabled
属性。
注释
请记住将时区配置为符合要求,因为协调世界时(UTC)是时区的默认设置。
清理资源
如果不再需要虚拟机,请按照以下步骤将其删除:
- 导航到左侧的虚拟机概述页面
- 从顶部中间选项中选择“删除”。
- 按照提示删除虚拟机。
有关如何删除虚拟机的详细信息,请参阅删除 VM。
后续步骤
了解 VM 的尺寸以及如何调整 VM 大小: