Terraform GCP startup script local file instead of inline

Re-run custom startup scripts by logging into the instance and running.

sudo google_metadata_script_runner --script-type startup

And also to enable full debugging, do this

sudo DEBUG=1 google_metadata_script_runner

To reference a file in your GCE VM declarations just use the file function to read the contents from your selected file. For example:

resource "google_compute_instance" "default" {
  …
  metadata_startup_script = "${file("/path/to/your/file")}"
}

On a similar note, you can also use the template_file data source to perform token replacement on a template file and then reference the resolved file content in your GCE VM declaration. For example:

data “template_file” “default” {
  template = “${file(“/path/to/your/file”)}”
  vars = {
    address = “some value“
  }
}

resource "google_compute_instance" "default" {
  …
  metadata_startup_script = "${data.template_file.default.rendered}"
}

References:

  • https://www.terraform.io/docs/providers/google/r/compute_instance.html
  • https://www.terraform.io/docs/configuration-0-11/interpolation.html#file-path-
  • https://www.terraform.io/docs/providers/template/d/file.html