Automate VM configuration with startup scripts in GCP

Google Cloud Platform (GCP) gives you the option to add a startup script to your instance. The script will run every time the instance is started. The startup script can be a Windows batch script, PowerShell or a shell script if using Linux. For Windows instances you have the option to add a sysprep-specialize script that will run once during the initial sysprep phase of the instance.
In this post I wanted to talk only about startup scripts. They are an alternative for the automatic configuration instances. You can specify the startup script directly in the gcloud command by typing the commands within quotes, or as a local script where you specify the path, or as a script stored in a Storage Bucket. You can also do it in the Cloud Console (see image below).
Below is an example of  creating an instance with a PowerShell script (C:\Temp\download-and-create-db.ps1) that is run every time the instance is restarted.

You specify the startup script with the parameters “–metadata-from-file windows-startup-script-ps1=” if using a PowerShell script. For other options see documentation about Running Startup Scripts.

Example: Recreating a database on startup

As an example, lets say that you need to reload a fresh copy of a database every day. You could create a backup of the database from your master server and every day reload that database in multiple servers around the world. Or, it could be that you have multiple database servers running behind a load balancer all of them with a copy of the database. You can create a PowerShell script that automatically loads a fresh copy of the database just by restarting the server. The sample script (download-and-create-db.ps1) can be found here. This sample script will restore a copy for the AdventureWorks2014 database.
There are other cases where you can use a startup script. Some that come to mind are the following:

  1. Standardize how to configure instances
  2. Add newly created instances automatically into a Windows Domain
  3. Test different types of server configurations

Note: If you need to run the startup script only once, you could add logic into the script to skip doing any work if it detects that there is nothing to do. You could also clear the metadata related to the startup script after the instance has started once. The command to clear the metadata about the startup script is:

If hope this post gets you started to on how to use startup scripts for the automatic configuration of instances.