18

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.

0

2 Answers 2

29

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:

Sign up to request clarification or add additional context in comments.

2 Comments

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
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 or by checking its logs in Stackdriver or by accessing the VM and reading the logs directly.
5

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

1 Comment

Debug works with "--debug" at the end: sudo DEBUG=1 google_metadata_script_runner --script-type startup --debug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.