Every new Compute Engine VM starts as a blank slate: a fresh OS with none of your packages, users, firewall settings, or application files. You could configure each machine by hand, but that does not scale — and it does not survive rebuilds. GCE startup scripts solve this cleanly. They are scripts that run automatically every time a Compute Engine instance boots, letting you install software, create users, pull configuration, and register the machine with your infrastructure without ever logging in.

This guide explains when GCE startup scripts run, how to pass them through instance metadata, how to view their output in the serial console and Cloud Logging, how to write idempotent scripts that are safe to rerun, and how to debug the failures you will inevitably meet. We also cover the Windows equivalents and the difference between instance-level and project-level scripts.
Prerequisites
To follow along you need:
- A Google Cloud project with the Compute Engine API enabled and billing attached.
- The
gcloudCLI installed and authenticated. New to it? Start with our walkthrough of installing gcloud CLI on Linux and running your first commands. - A basic familiarity with bash scripting and with creating Compute Engine VMs — see our guide on how to create and harden a Compute Engine VM for the security side.
When Do GCE Startup Scripts Run?
A startup script executes on every boot of the instance — not just the first one. The guest environment (the set of Compute Engine agent tools preinstalled on official Google images) fetches the script from the metadata server early in the boot process and runs it as root. That means your script must be safe to run repeatedly: a package install that assumes a fresh machine will fail or misbehave on the second boot unless you write it idempotently.
On Linux, output goes to the serial console and to the system journal. On Windows, the script runs at boot and its events are recorded as GCEMetadataScripts events. Scripts are subject to the metadata size limit (values up to 256 KB, 512 KB total metadata), so very large bootstrap payloads should live in a Cloud Storage bucket or a startup-script URL instead of being pasted inline.
Step 1: Write Your Startup Script
Create a local file, for example startup-script.sh. Here is a realistic example that installs Nginx, writes a status page, and enables a firewall-friendly service on Debian/Ubuntu:
#!/bin/bash
set -e
# Install Nginx only if it is not already installed (idempotent)
if ! dpkg -l nginx 2>/dev/null | grep -q '^ii'; then
apt-get update
apt-get install -y nginx
fi
# Write a simple status page
cat > /var/www/html/index.html <<'EOF'
<html><body><h1>Provisioned by GCE startup script</h1></body></html>
EOF
# Make sure the service is enabled and running
systemctl enable nginx
systemctl start nginx
echo "Startup script finished successfully" > /var/log/startup-script.log
A few conventions matter here. The script runs as root, so you do not need sudo (and should not use it, since the environment differs from an interactive shell). Always use absolute paths, set set -e so the script stops on the first error, and never assume a previous run left the machine in a particular state.
Step 2: Pass the Script Through the startup-script Metadata Key
Compute Engine discovers startup scripts through reserved metadata keys. For Linux, the key is startup-script. The cleanest way to attach a script at creation time is --metadata-from-file, which reads the value from a local file:
gcloud compute instances create web-server-1 \
--zone=asia-southeast1-b \
--machine-type=e2-micro \
--image-family=debian-12 \
--image-project=debian-cloud \
--metadata-from-file startup-script=./startup-script.sh \
--tags=http-server
You can also pass short scripts inline with --metadata, and you can add a script to an existing instance, which takes effect on its next boot:
# Inline variant for very short scripts
gcloud compute instances create web-server-2 \
--zone=asia-southeast1-b \
--metadata startup-script='#! /bin/bash
apt-get update
apt-get install -y htop'
# Attach a startup script to an existing (stopped or running) instance
gcloud compute instances add-metadata web-server-1 \
--zone=asia-southeast1-b \
--metadata-from-file startup-script=./startup-script.sh
If your script is hosted publicly — for example in a Cloud Storage bucket with public read access — use the startup-script-url key instead. The guest environment downloads it at boot. Prefer this over pasting huge scripts into metadata.
Instance metadata versus project metadata
The same startup-script key can be set at the project level, in which case it applies to every instance in the project. Instance-level metadata overrides project-level metadata, so you can set a project-wide baseline (hardening, monitoring agents, SSH key rotation) and specialize per instance. Check what is currently set with:
gcloud compute instances describe web-server-1 \
--zone=asia-southeast1-b \
--format='value(metadata.items)'
Step 3: View the Script Output
Once the instance boots, verify the script ran. The fastest check is the serial console output:
gcloud compute instances get-serial-port-output web-server-1 \
--zone=asia-southeast1-b
Look for the guest environment lines showing the script was fetched and executed, plus any output your script produced. For ongoing observability, the guest environment also forwards script output to Cloud Logging, where you can filter by the instance name and search for errors across a fleet of machines. Inside the VM, the systemd journal carries the same records:
sudo journalctl -u google-startup-scripts.service --no-pager
Startup Scripts on Windows
Windows VMs use their own set of metadata keys. The most common are windows-startup-script-ps1 (PowerShell), windows-startup-script-cmd, and windows-startup-script-bat. Example:
gcloud compute instances create win-server-1 \
--zone=asia-southeast1-b \
--machine-type=e2-medium \
--image-family=windows-2022 \
--image-project=windows-cloud \
--metadata-from-file windows-startup-script-ps1=./setup.ps1
To inspect the result, open the serial port 1 output in the Cloud Console and search for GCEMetadataScripts events, or check the Windows Event Viewer’s Application log. To rerun a Windows startup script manually, execute C:\Program Files\Google\Compute Engine\metadata_scripts\run_startup_scripts.cmd from an elevated prompt. Full details are in the official startup scripts documentation.
Writing Idempotent GCE Startup Scripts
Because the script runs on every boot, idempotency is the difference between a reliable fleet and a fleet that breaks on reboot. Follow these rules:
- Guard every mutation. Check whether a package, user, file, or service already exists before creating it. Prefer declarative tools (
systemctl enable, config files written with>) over appends. - Make downloads safe to repeat. Use
curl -oto a temp file followed by an atomicmv, or check a checksum before overwriting. - Keep secrets out of metadata. Startup scripts are visible to anyone with metadata read access on the instance. Fetch secrets from Secret Manager at runtime using the instance service account instead of embedding them.
- Log progress. Echo milestones to a log file (like
/var/log/startup-script.logabove) so the serial console tells a story when something fails at 3 a.m. - Set a timeout budget. Long-running package installs delay boot; consider backgrounding heavy work with
nohupafter the essentials are done, and make sure a reboot mid-install cannot corrupt state.
Troubleshooting GCE Startup Script Failures
The script never seems to run
First, confirm the metadata key is exactly startup-script (hyphens, not underscores) and that you are using an official Google image with the guest environment installed — custom images without it silently ignore the key. Then check the serial output for lines mentioning the metadata script runner. If you added metadata to a running instance, remember it only takes effect on the next boot; restart the instance.
The script runs but a command fails
Most failures come from environment differences. The script runs as root with a minimal PATH and no interactive shell profile, so commands that work over SSH may fail at boot. Use absolute paths (/usr/bin/apt-get rather than apt-get), export any variables you need explicitly, and avoid anything that waits for user input. With set -e, the first failing command stops the script — the serial console shows exactly which line failed.
Network-dependent steps fail on first boot
At the moment startup scripts run, the network is up but DNS or external endpoints may not be fully ready, especially in regions with slow metadata propagation. Add retries around apt-get update and downloads, or loop with a short sleep until connectivity works. A simple pattern:
for i in 1 2 3 4 5; do
apt-get update && break
echo "apt-get update failed, retrying in 10s (attempt $i)"
sleep 10
done
Metadata size errors
If gcloud rejects your metadata, the script exceeds the 256 KB per-value or 512 KB total limit. Move the payload to Cloud Storage and reference it with startup-script-url, or split configuration into a separate file fetched at runtime.
Conclusion
GCE startup scripts turn every boot into an automated provisioning run: write a root-level script, attach it with --metadata-from-file startup-script=..., and Compute Engine executes it before you ever connect. Read the output in the serial console or Cloud Logging, use the windows-startup-script-ps1 family on Windows, keep secrets in Secret Manager, and write every step idempotently so reboots are boring. Combined with instance templates and managed instance groups, startup scripts are the simplest path to truly reproducible VMs — define once, boot anywhere, and never configure a machine by hand again.