Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform GCP startup script local file instead of inline

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.

like image 526
Keith Wiley Avatar asked Aug 27 '19 21:08

Keith Wiley


1 Answers

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
like image 151
glytching Avatar answered Oct 01 '22 23:10

glytching