也许这个功能是后来添加的,但从 2021 年初开始,您可以使用google_compute_instance_template的可选metadata_startup_script参数来指定一个脚本,该脚本将在每次从模板创建的任何实例启动时运行:
resource "google_compute_instance" "hubmud" {
name = "hubmud"
machine_type = "f1-micro"
tags = ["buildserver", "jenkins", "central", "terraformer"]
tags = [ "http-server" ]
zone = "us-central1-b"
disk {
image = "ubuntu-1404-trusty-v20160406"
}
network_interface {
network = "default"
access_config {}
}
# As per the documentation for google_compute_instance_template (https://registry.terraform.io/providers/hashicorp/google/latest/docs/data-sources/compute_instance_template#metadata_startup_script)
# you can set either metadata.startup-script or metadata_startup_script
# to the contents of a file that will be added to the metadata of
# any instance created from the template.
# In both cases the script will run each time the instance starts.
# The difference is that if metadata_startup_script is used and the metadata
# value is changed the instance will be destroyed and recreated before
# running the new script.
metadata_startup_script = file("${path.module}/installations.sh")
service_account {
scopes = ["userinfo-email", "compute-ro", "storage-ro"]
}
}
请注意,此机制需要操作系统支持,但正如google_compute_instance 上基础参数的文档所指出的那样:
“大多数基于 linux 的映像将在每次启动时在 shell 中运行 metadata.startup-script 的内容。至少,Debian、CentOS、RHEL、SLES、Container-Optimized OS 和 Ubuntu 映像支持此密钥。Windows 实例需要其他键取决于脚本的格式和您希望它运行的时间。”
早在 Ubuntu 16.04 就进行了测试,该版本在本月底达到了 LTS 的 EOL。所以这个功能已经存在了 5 年多。不清楚它是否在很久以前就被 GCP Terraform 提供者公开了,但它现在可以完美运行。