14
votes

Lots of examples exist online that show how to run a startup script on a VM deployed on GCP/GCE with Terraform, but they all use inline startup scripts, with all the startup script code included in the terraform compute.tf file. This is done either with a single line for the startup script, or with <<SCRIPT[script code]SCRIPT for multiple lines. I haven't found a single example showing a way to assign the startup script parameter to another file on local disk, perhaps in the same directory as compute.tf. It is quite a mess to clutter compute.tf with hundreds of lines of startup script. Isn't there a better way to do this?

I realize I could write a wrapper script that combines a compute.tf and a separate startup file into a single compute.tf and then runs terraform, but I'm seeking a more direct route, assuming one exists.

Thank you.

2

2 Answers

16
votes

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:

3
votes

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