Google Cloud Startup Scripts allow you to run commands automatically when a Compute Engine VM instance boots. This is super useful for tasks like installing packages, configuring web servers, and setting up environments without manual effort.
In this tutorial, weβll walk through creating a VM in Google Cloud Platform (GCP) and using a startup script to install Nginx and serve a custom HTML page.
π Step 1: Enable the Compute Engine API
Before creating a VM, ensure that the Google Compute Engine API is enabled in your project.
π Step 2: Create a VM Instance
Navigate to:
Google Cloud Console β Compute Engine β VM Instances β Create Instance
Fill in the details as below:
- Name: demo2-vm-startupscript
- Labels: environment: dev
- Region: us-central1
- Zone: us-central1-a
- Machine Configuration:
- Series: E2
- Machine Type: e2-micro (free-tier eligible)
- Operating system and storage
- Availability Policies: Standard provisioning
- Display Device: unchecked (default)
- Confidential VM Service: unchecked (default)
- Container: unchecked (default)
- Boot Disk: leave to defaults (Debian/Ubuntu recommended)
- Identity & API Access:
- Service Account: Compute Engine default
- Access Scopes: Allow default access
- Firewall: β Allow HTTP traffic
π Step 3: Add Startup Script
Expand Advanced Options β Management β Automation β Startup Script
Paste the following script:
#!/bin/bash
sudo apt install -y telnet
sudo apt install -y nginx
sudo systemctl enable nginx
sudo chmod -R 755 /var/www/html
HOSTNAME=$(hostname)
sudo echo "<!DOCTYPE html> <html> <body style='background-color:rgb(250, 210, 210);'> <h1>Welcome to Latchu@DevOps - WebVM App1 </h1> <p><strong>VM Hostname:</strong> $HOSTNAME</p> <p><strong>VM IP Address:</strong> $(hostname -I)</p> <p><strong>Application Version:</strong> V1</p> <p>Google Cloud Platform - Demos</p> </body></html>" | sudo tee /var/www/html/index.html
π Step 4: Configure Additional Settings
- Description: demo2-vm-startupscript
- Deletion Protection: β Enable it
- Reservations: leave default
- Metadata: leave empty
- Data Encryption: leave defaults
Finally, click Create.
π Step 5: Access the webpage
The instances are running and the webpage is accessible through the browser.
π Step 6: Delete the VM
If you select the VM, youβll notice the Delete option is disabled. To remove it, go to VM > Edit > Deletion protection, uncheck Enable deletion protection, and save the changes.
Now you can safely delete this VM since itβs no longer needed.
Top comments (0)