【问题标题】:Google Cloud - gcloud script using startup script stored on Cloud StorageGoogle Cloud - 使用存储在 Cloud Storage 上的启动脚本的 gcloud 脚本
【发布时间】:2021-06-27 18:26:47
【问题描述】:

在 GCP 云中,我想使用 gcloud 启动脚本部署并配置 Windows Server。我准备并测试了 PowerShell 脚本(用于 Windows Server 配置)。我已将此 PowerShell 脚本上传到 Cloud Storage。我已经为 VM 部署准备了 gcloud 命令脚本(我保存为 .sh 脚本的 gcloud 命令脚本)。我将此 .sh 脚本上传到 Cloud Shell 中。在 .sh 脚本中,我使用元数据启动脚本 section--metadata=startup-script-url="gs://bucketName/Server-Configuration-Script.ps1。在Server-Configuration-Script.ps1 PowerShell 脚本中,我有 4 个必须传递的参数,位于 srcipt 参数之下。

param (
    [Parameter(Mandatory=$true)][string] $paramA,
    [Parameter(Mandatory=$true)][string] $paramB,
    [Parameter(Mandatory=$true)][string] $paramC,
    [Parameter(Mandatory=$true)][string] $paramD
 )

我的问题是如何在我的 .sh 脚本的启动脚本部分 --metadata=startup-script-url="gs://bucketName/Server-Configuration-Script.ps1 中使用所有四个参数?

【问题讨论】:

  • 你知道启动VM前的参数吗?
  • 是的,但我不想使用硬编码 im powershell 脚本的值。
  • 我个人更喜欢 Compute Engine 自定义元数据而不是硬编码值。这让您有更大的灵活性和在其他 VM 上重用相同脚本的能力,而无需更改脚本的内容。有什么理由对值进行硬编码?你会在其他虚拟机上使用不同参数的相同脚本吗?
  • 正如我所提到的,我不会使用硬编码值。在存储在 Cloud Storage 存储桶中的 PowerShell 代码中,我有四个参数,在上面的帖子中列出。在我的 cloud shell gcloud 命令中,我想使用元数据部分 --metadata=startup-script-url="gs://bucketName/Server-Configuration-Script.ps1 -paramA -paramB -paramC -paramD,但我不确定如何创建此命令,如何传递 parama paramA ...D。
  • 如果传递启动脚本url,不能提供参数。这就是为什么您需要在其他地方提供它们,例如在元数据中

标签: powershell google-cloud-platform gcloud


【解决方案1】:

我建议您在 VM 的元数据中设置参数的值。

gcloud compute instances add-metadata instance-name \
    --metadata ParamA=4,ParamB=25,ParamC=1,ParamD="Windows Server 2016"

然后,在启动脚本中,你可以这样获取它们

paramA=$(curl http://metadata.google.internal/computeMetadata/v1/instance/attributes/ParamA -H "Metadata-Flavor: Google")

编辑 1

在windows机器上测试后,我发现如何在启动时做

Invoke-RestMethod -H @{'Metadata-Flavor'='Google'} -Uri 'http://metadata.google.internal/computeMetadata/v1/instance/attributes/ParamA'

Curl 是 Invoke-WebRequest 的别名,需要对当前用户进行 Internet Explorer 配置的第一次初始化。当您运行启动脚本时,它以系统帐户运行,并且您没有为该用户配置 IE。

我不擅长 powershell。当我将输出重定向到文件时,该命令有效,例如> c:\Windows\Temp\paramA.txt。把代码改成比我能做的更好的 PS 脚本!

【讨论】:

  • 所以你建议把这个 curl 请求 --> paramA=$(curl http://metadata.google.internal/computeMetadata/v1/instance/attributes/ParamA -H "Metadata-Flavor: Google") 放到我的启动 PowerShell 脚本中?
  • 是的,不需要外部参数,而是在脚本开头初始化它们
  • 我使用了你在启动 PowerShell 脚本中提到的参数 --> $ParamA=$(curl http://metadata.google.internal/computeMetadata/v1/instance/attributes/ParamA -H "Metadata-Flavor: Google")。不幸的是,该解决方案不起作用,部署后仍然没有配置VM :(这不是Linux VM,而是Windows VM,我认为没有安装curl软件。
  • 我可以在带有 PowerShell 的 Windows 工作站上使用 CURL,尽管在 GCE 上是一样的。
  • 好的,我已经更正了 gcloud 命令中的元数据部分,现在它可以工作了,谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2017-11-29
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多