Skip to the content
Fabian Lee : Software EngineerFabian Lee : Software Engineer
Cloud Operations and Development
  • Monitoring
  • Logging
  • Containers
  • Python

Terraform: invoking a startup script for a GCE google_compute_instance

May 28, 2021
Categories: Virtualization

You can bake a startup script directly into the creation of your GCE compute instance when using Terraform.  Although complex post-configuration should be left to tools such as Ansible, essential bootstrap type commands or custom routes for instances in private subnets are reasons why you might need to use this hook.

Below is an example of an inline bash script specified in the ‘metadata_startup_script’ parameter that logs a test message and then queries the metadata service for its private IP address.

resource "google_compute_instance" "myinstance" {
  ...

  metadata_startup_script = <<SCRIPT
    echo test of user_data | sudo tee /tmp/user_data.log
    curl -sf -H 'Metadata-Flavor:Google' http://metadata/computeMetadata/v1/instance/network-interfaces/0/ip | sudo tee -a /tmp/user_data.log
    SCRIPT
}

You can also reference the contents of a local file (local to terraform)

resource "google_compute_instance" "myinstance" {
  ...

  metadata_startup_script = file("${path.module}/startup.sh")
}

Or you can use a ‘template_file’ as shown below.

data "template_file" "default" {
  template = file("${path.module}/startup.sh")
  vars = {
    foo = "bar"
  }
}

resource "google_compute_instance" "myinstance" {
  ...

  metadata_startup_script = data.template_file.default.rendered
}

REFERENCES

terraform, google_compute_instance

Categories: Virtualization Tags: GCE, google_compute_instance, metadata_startup_script, startup, terraform

Post navigation

← Terraform: invoking a startup script for an EC2 aws_instance
Azure: installing the Azure CLI on Ubuntu →
© 2025 Fabian Lee : Software Engineer