如何在 Google Cloud VM 上运行 bash 脚本?

问题描述

我在 GCP 上找到了这个 VM 实例的自动关闭脚本,并尝试将其添加到 VM 的元数据中。

这是关闭脚本的 link

配置将其设置为在 20 分钟后空闲 VM 将关闭,但已经过了几个小时,它从未关闭。将脚本添加到 VM 元数据后,我还需要执行其他步骤吗?

添加的元数据脚本:

enter image description here

解决方法

启动脚本在 VM 启动时执行。如果您在启动时执行“关闭脚本”,它将无事可做。此外,为了使其正常工作,必须创建适当的服务,并且它将使用此脚本来检测和关闭 VM,以防它处于空闲状态。 所以 - 即使主脚本 ashutdown 在启动时执行并且没有空闲,它也没有做任何事情。而且由于服务不在那里再次运行它,您的实例将无限期地运行。

为此,您需要在相关 VM 上安装所有内容;

将所有三个文件下载到虚拟机中的某个目录,例如使用 curl:

curl -LJO https://raw.githubusercontent.com/GoogleCloudPlatform/ai-platform-samples/master/notebooks/tools/auto-shutdown/ashutdown
curl -LJO https://raw.githubusercontent.com/GoogleCloudPlatform/ai-platform-samples/master/notebooks/tools/auto-shutdown/ashutdown.service
curl -LJO https://raw.githubusercontent.com/GoogleCloudPlatform/ai-platform-samples/master/notebooks/tools/auto-shutdown/install.sh

使 install.sh 可执行:sudo chmod +x install.sh

运行它:sudo ./install.sh

这应该会在您的系统中安装并运行 ashutdown 服务。

您可以使用 service ashutdown status 检查它是否正在运行。

这些说明适用于 Debian 系统,因此如果您运行的是 CentOS 或其他版本的 Linux,它们可能会有所不同。