17

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.

Keith Wiley
  • 683
  • 2
  • 6
  • 14

2 Answers2

24

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:

Saurabh
  • 5,176
  • 4
  • 32
  • 46
glytching
  • 44,936
  • 9
  • 114
  • 120
  • How can you see the output of the `metadata_startup_script` when this is executed? Currently the script is executed with this syntax but I do not see any script output / errors – bp2010 Aug 28 '19 at 11:27
  • 4
    Regardless of how the startup script is supplied (whether in-line or using the file function) the script is executed _on_ the GCE VM so you'll see its output in [serial port output](https://cloud.google.com/compute/docs/instances/viewing-serial-port-output) or by checking its logs in Stackdriver or by accessing the VM and reading the logs [directly](https://cloud.google.com/compute/docs/startupscript#rerunthescript). – glytching Aug 28 '19 at 11:36
4

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
Ajay Kharade
  • 1,469
  • 1
  • 17
  • 31