Google Cloud Credit Top-up How to Run Startup Scripts on Google Cloud VM
Introduction: Why Bother with Startup Scripts?
Let's face it—setting up servers manually is about as fun as watching paint dry. Every time you spin up a new VM, you have to SSH in, install packages, configure settings... it's a tedious chore that nobody wants. Enter startup scripts: the secret weapon for lazy (efficient) admins. These scripts run automatically when your VM boots up, automating everything from software installation to initial setup. Think of them as your VM's personal assistant, ready to handle all the boring stuff so you can focus on the fun part—like planning your next coffee break.
Method 1: The Visual Approach – Using Google Cloud Console
Not a fan of typing commands? No problem. Google Cloud's web console makes it easy to add startup scripts with a few clicks. Here's how to do it:
Google Cloud Credit Top-up Creating a New VM with Startup Script
When creating a new VM instance in the Cloud Console, look for the "Management, security, disks, networking, sole tenancy" section. Click "Management" to expand it, then scroll down to "Metadata". Here, you'll find the "Startup script" field. Paste your script right in there. For example:
#!/bin/bash
apt-get update
apt-get install -y apache2
echo "Hello from Google Cloud!" > /var/www/html/index.html
systemctl start apache2
Simple, right? The console handles all the backend stuff—no need to remember complex CLI commands. Just hit "Create" and your VM will automatically run this script on boot. No more manual setup for each new instance. It's like giving your VM a to-do list and letting it do the work while you sip coffee.
Method 2: CLI Wizardry with gcloud
For those who prefer the command line (or just hate clicking buttons), the gcloud tool is your best friend. Let's break it down step by step.
Command Breakdown
To create a VM with a startup script via CLI, use the gcloud compute instances create command with the --metadata flag. Here's a basic example:
gcloud compute instances create my-vm \\
--zone=us-central1-a \\
--metadata startup-script='#!/bin/bash\\necho "Hello World" > /tmp/hello.txt'
Notice the single quotes around the script, and the escaped newline character (\\n). But wait—what if your script is longer than a couple of lines? You can use the --metadata-from-file flag to read from a file:
gcloud compute instances create my-vm \\
--zone=us-central1-a \\
--metadata-from-file startup-script=./startup.sh
This way, you can write your script in a local file (with proper permissions), then reference it directly. It's cleaner and avoids escaping headaches. Just make sure your script file has execute permissions (chmod +x startup.sh), though the Google Guest Environment usually handles this automatically.
Google Cloud Credit Top-up Method 3: Scaling Up with Instance Templates
Running a single VM is easy, but what if you're managing a fleet of VMs? That's where instance templates shine. By creating a template with your startup script, you can deploy multiple VMs with consistent configurations in one go.
Template Setup Steps
First, create an instance template via the Cloud Console or CLI. In the console, go to "VM instances" > "Instance templates" and click "Create template". In the template configuration, navigate to "Management" > "Metadata" and add your startup script under "Startup script". Alternatively, use gcloud:
gcloud compute instance-templates create my-template \\
--metadata startup-script='#!/bin/bash\\necho "Hello from template!" > /tmp/hello.txt'
Once the template is created, you can use it to create new VMs or managed instance groups. Any VM launched from this template will automatically execute the startup script. It's like having a cookie cutter for your VMs—every single one comes out exactly the same, every time.
Applying Templates to Existing VMs
Wait, can you update existing VMs with a new template? Not directly, but you can create a new instance group with the updated template and migrate your workloads. For stateless services, this is a breeze. For stateful systems, you might need to use rolling updates to replace instances one by one. But hey, at least you won't have to manually tweak each VM individually.
Troubleshooting: When Things Go South
Even the best scripts can go wrong. Maybe you forgot a semicolon, or the script doesn't have execute permissions, or the system runs out of disk space. Don't panic—here's how to debug.
Checking Logs
Google Cloud logs startup script execution in /var/log/syslog on most Linux distributions. You can also use the gcloud logging read command to view logs directly from the console. For example:
gcloud logging read 'resource.type="gce_instance" AND resource.labels.instance_id="your-instance-id"' --project=your-project-id
Look for lines containing "startup-script" or "GoogleCompute". If your script failed, the logs will usually tell you why—like a missing package or syntax error.
Common Mistakes and Fixes
Mistake 1: Forgetting the shebang
If your script starts without #!/bin/bash, the system might not know how to execute it. Always include the shebang at the top of your script. It's like writing "Dear VM" before giving instructions—it sets the context.
Mistake 2: Permission issues
Some commands require sudo, but startup scripts run as root by default. So if you're trying to install software, you don't need sudo—just run the commands directly. However, if you're writing files to directories requiring root access (like /var/www), ensure the script has permission to do so. If you're unsure, test the script manually first.
Mistake 3: Network-dependent tasks
Startup scripts run as soon as the VM boots, but network services might not be ready yet. If your script depends on internet access (e.g., downloading packages), add a delay or use a loop to check for connectivity before proceeding. For example:
#!/bin/bash
while ! ping -c 1 google.com; do
sleep 1
done
apt-get update
That way, your script won't fail because the network isn't ready yet.
Real-World Examples You Can Steal (Legally)
Let's look at some practical scripts you can adapt for your own projects.
Web Server Auto-Setup
Here's a script to set up a basic Apache web server with a custom homepage:
#!/bin/bash
# Update system and install Apache
apt-get update
apt-get install -y apache2
# Create custom homepage
echo "<html><body><h1>Welcome to My Cloud Server!</h1></body></html>" > /var/www/html/index.html
# Start Apache service
systemctl start apache2
systemctl enable apache2
Deploy this to any VM, and boom—you've got a working web server. No SSH, no manual config. Just deploy, and it's ready to serve content immediately. Perfect for quick demos or testing environments.
Docker Container Deployment
Need to run a containerized app without manual setup? This script installs Docker and launches an Nginx container:
#!/bin/bash
# Install Docker
apt-get update
apt-get install -y docker.io
# Start Docker service
systemctl start docker
systemctl enable docker
# Run Nginx container
docker run -d -p 80:80 nginx
After deployment, your VM will automatically host an Nginx server accessible on port 80. It's a zero-effort way to get containers running. Just make sure your VM has a public IP and firewall rules allow HTTP traffic.
Python Flask App Setup
Here's a script to deploy a simple Flask app:
#!/bin/bash
# Install Python and dependencies
apt-get update
apt-get install -y python3-pip python3-venv
# Create a virtual environment and install Flask
python3 -m venv /opt/flask-app
source /opt/flask-app/bin/activate
pip install flask
# Create a simple Flask app
echo "from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello from Google Cloud!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)" > /opt/flask-app/app.py
# Run the app
nohup python /opt/flask-app/app.py &
This script sets up a minimal Flask application that listens on port 8080. It's perfect for lightweight web services or API endpoints. Just deploy it to a VM, and your app starts automatically—no manual SSH needed. Of course, remember to adjust firewall rules to allow traffic on port 8080!
Best Practices for Foolproof Scripts
With great power comes great responsibility (and occasional script fails). Here's how to avoid headaches:
Security Tips
Never hardcode secrets like passwords or API keys in startup scripts. If you need to access secure resources, use Google Cloud IAM roles or Secrets Manager. For example, instead of storing a database password in the script, grant your VM a service account with access to Secrets Manager, then fetch the secret dynamically at runtime. That way, your credentials stay safe—even if someone stumbles upon your script.
Keeping Scripts Clean and Maintainable
As your scripts grow, keep them modular. Break complex tasks into functions and comments. For example:
#!/bin/bash
setup_webserver() {
apt-get update
apt-get install -y apache2
echo "Welcome!" > /var/www/html/index.html
systemctl start apache2
}
install_docker() {
apt-get install -y docker.io
systemctl start docker
docker run -d -p 80:80 nginx
}
# Execute selected setup
if [ "$1" == "web" ]; then
setup_webserver
elif [ "$1" == "docker" ]; then
install_docker
fi
This way, you can call specific parts of your script based on parameters, making it reusable for different scenarios. And comments? They're your future self's best friend. Write them like you're explaining to a junior developer—because someday, you'll be that junior developer trying to fix your own code.
Conclusion: Let Your VM Do the Heavy Lifting
Startup scripts are a game-changer for cloud management. They turn tedious manual setups into automatic, repeatable processes. Whether you're deploying a single VM or scaling to thousands, scripting your VM's first steps saves time, reduces errors, and lets you focus on higher-value tasks. So the next time you spin up a new instance, remember: don't do the work yourself. Let your VM handle it with a startup script. After all, you wouldn't want to be the one typing every command—right?

