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