如何将环境变量注入到 gcloud compute instances create 的启动脚本中?

How can I inject an environment variable into the startup script for gcloud compute instances create?

我正在使用 gcloud compute instances create 命令创建 GCE VM,我正在使用 --metadata-from-files 参数传入启动 shell 脚本以进行一些配置。

但是,我需要为各种环境变量预填充指定值,以便启动脚本工作。它们不能硬编码到启动脚本中,因为它们对于我正在编写的整个脚本的不同用户来说是不同的(例如,传递到新实例中的环境变量可能基于 $USER 调用脚本)。

我也尝试使用 --metadata 参数添加键值对,但这不起作用,并且引用的 shell 变量在启动脚本的执行中仍然未绑定。

我如何发出 gcloud compute instances create 命令转发一些环境变量,这些变量将填充到环境中供启动脚本使用它们?

--metadata 参数似乎应该是正确的,因为 docs

Metadata to be made available to the guest operating system running on the instances.

您应该能够使用此文档生成适当的 curl 命令来提取您的元数据: https://cloud.google.com/compute/docs/storing-retrieving-metadata

然后您可以使用提取的值来设置您的环境变量。

(已编辑以修复 URL。)