How to Use Startup Script in GCP Compute Engine
In GCP, use a
startup script to run commands automatically when a Compute Engine instance boots. You add the script in the instance's metadata under the key startup-script. This script can be a shell script that installs software or configures the instance.Syntax
A startup script in GCP is a shell script added to the instance metadata with the key startup-script. When the instance starts, GCP runs this script automatically.
Parts explained:
- startup-script key: Metadata key where the script is stored.
- Script content: Shell commands to run on boot.
- Instance metadata: Place to add the script so GCP knows to run it.
bash
gcloud compute instances add-metadata INSTANCE_NAME --metadata startup-script='#!/bin/bash\necho Hello, world! > /var/log/startup-script.log'Example
This example shows how to create a new Compute Engine instance with a startup script that updates packages and installs nginx web server automatically on boot.
bash
gcloud compute instances create example-instance \
--metadata startup-script='#!/bin/bash
sudo apt-get update
sudo apt-get install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
echo "Nginx installed and started" > /var/log/startup-script.log'Output
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/example-instance].
Common Pitfalls
Common mistakes when using startup scripts in GCP include:
- Not starting the script with
#!/bin/bash, causing it not to run properly. - Forgetting to make commands run with
sudowhen needed, leading to permission errors. - Not escaping quotes properly when passing scripts via command line.
- Assuming the script runs instantly; it runs asynchronously during boot.
Always check the log file /var/log/startup-script.log on the instance to debug.
bash
Wrong way: gcloud compute instances add-metadata my-instance --metadata startup-script='echo Hello' Right way: gcloud compute instances add-metadata my-instance --metadata startup-script='#!/bin/bash\necho Hello > /var/log/startup-script.log'
Quick Reference
| Key | Description |
|---|---|
| startup-script | Metadata key to add your shell script for instance startup |
| #!/bin/bash | Shebang line to specify the script interpreter |
| sudo | Run commands with root privileges if needed |
| /var/log/startup-script.log | Default log file to check script output and errors |
| gcloud compute instances add-metadata | Command to add or update metadata on an instance |
Key Takeaways
Add your shell commands under the metadata key 'startup-script' to run them on instance boot.
Always start your script with '#!/bin/bash' to ensure it runs correctly.
Use 'sudo' for commands that need root access inside the script.
Check '/var/log/startup-script.log' on the instance to see script output and debug errors.
Escape quotes properly when passing scripts via command line to avoid syntax errors.