Run shutdown scripts

Linux Windows

Create and run shutdown scripts that execute commands right before a virtualmachine (VM) instance is stopped or restarted. This is useful if yourely on automated scripts to start up and shut down instances, allowinginstances time to clean up or perform tasks, such as exporting logs, or syncingwith other systems.

Shutdown scripts are especially useful for VMs in amanaged instance group with anautoscaler. If the autoscaler shuts down aVM in the group, the shutdown script runs before the VMstops and the shutdown script performs any actions that you define.The script runs during the limitedshutdown period before theVM stops. For example, your shutdown script might copy processed datato Cloud Storage or back up any logs.

Shutdown scripts function very similarly to startup scripts. Much of thedocumentation forstartup scripts alsoapplies for shutdown scripts.

For both shutdown and reboot tasks, VMs always run shutdown scripts as follows:

  • For Linux VMs, by using theroot user.
  • For Windows VMs, by using theSystem account.
Note: A VM-level or zonal-level shutdown script takes precedence over aproject-level shutdown script. If you configure a shutdown script either on aspecific VM or on VMs in a specific zone in your project, then the project-levelscript isn't executed on that VM. For information about how to add aproject-level shutdown script, seegcloud compute project-info add-metadata.

Prerequisites

To run scripts stored in metadata on a VM instance, theguest environment must be installed and running.

  • The guest environment includes theguest agent (for example, google-guest-agent on Linux)that reads the script content or URL from the instance's metadata and initiates execution.
  • All public Compute Engine images come with the guest environmentpreinstalled.
  • If you create a custom image, you mustmanually install the Google Guest Environment to ensurescripts from metadata and other Google Cloud features function properly.

Before you begin

Permissions required for this task

To perform this task, you must have the followingpermissions:

  • All permissions required tocreate an instance
  • compute.instances.setMetadata on the instance

Specifications

The following sections outline the specifications for shutdown scripts.

Limitations

There are some limitations to note when using shutdown scripts:

  • Compute Engine executes shutdown scripts only on abest-effort basis. In rare cases, Compute Engine cannot guaranteethat the shutdown script will complete.
  • On Windows, the Local Group Policy is used to launch the shutdown script.
    • The installation package configures the Local Group PolicyComputer Configuration/Windows Setting/Scripts (Startup/Shutdown)setting to launch the script upon system shutdown.

Shutdown script invocation

Shutdown scripts are triggered when the instance shuts down after any of thefollowing events happen:

  • You do the following:

  • Compute Engine stops an instance as part of a programmed stop ordelete operation.

  • Compute Engine stops a Spot VM or preemptibleinstance as part of thepreemption process.

A shutdown script can be of any file type. If there is a shutdown script presentin the instance, then Compute Engine does the following:

  1. Copies the script to a local file in the instance.
  2. Sets permissions on the file to make the script executable.
  3. Executes the file when the instance shuts down.

You could, for example, provide a Python script instead of a bash script.Keep in mind that Compute Engine runs the script verbatim,regardless of the type of script.

To execute a script that is not bash, add a shebang line at the top of the fileto let the operating system know which interpreter to use. For example, for aPython script, you can add a shebang line like:

#!/usr/bin/python

Shutdown script running time

Your shutdown scripts start running when Compute Engine sets theinstance state toSTOPPING. Your scripts must complete before the instanceis fully stopped, which is when its state changes toTERMINATED. The time theinstance takes to reach theTERMINATED state varies depending on theinstance type.

If your scripts take longer than the time it takes for the instance to stop,then Compute Engine forcefully stops the scripts, which can lead todata loss or incomplete tasks. To prevent this,stop the instance from within its guest OS.This approach keeps the instance state toSTOPPING until your shutdown scriptsfinish running.

Use a local shutdown script

A local shutdown script is a script that lives on your local computer.Pass in a local shutdown script either as a file or by giving the contentsdirectly to Compute Engine.

Shutdown scripts can perform as many actions as you need, but if youare passing in the file locally, your script cannot exceed the metadata valuelength limit of 256 KB. To use a script that exceeds the length limit,store your file on Cloud Storage. SeeUse shutdown script from Cloud Storage formore information.

Provide a shutdown script file

You can only pass in a local shutdown script file through thegcloudcommand-line tool.

gcloud

To pass in a local shutdown script file, supply the--metadata-from-fileflag, followed by a metadata key pair,shutdown-script=PATH/TO/FILE, wherePATH/TO/FILE is a relative path to the shutdown script. For example:

gcloud compute instances create example-instance \    --metadata-from-file shutdown-script=examples/scripts/install.sh

Terraform

To specify a shutdown script directly, use thegoogle_compute_instanceresource with the path to the shutdown script in the metadata.

resource "google_compute_instance" "shutdown_content_from_file" {  name         = "instance-name-shutdown-content-from-file"  machine_type = "f1-micro"  zone         = "us-central1-c"  metadata = {    # Shuts down Apache server    shutdown-script = file("${path.module}/shutdown-script.sh")  }  boot_disk {    initialize_params {      image = "debian-cloud/debian-11"    }  }  network_interface {    # A default network is created for all Google Cloud projects    network = "default"    access_config {    }  }}

Provide shutdown script contents directly

Alternatively, you can pass in the contents of your shutdown script directly.

Console

In Google Cloud console, specify a shutdown script directly using theshutdown-script metadata key:

  1. Go to theCreate an instance page.

    Go to Create an instance

  2. Specify the VM details.

  3. Expand theAdvanced options section.

  4. ExpandManagement, and do the following:

    1. In theMetadata section, clickAdd item.
    2. In theKey field, entershutdown-script for the metadata key.
    3. In theValue field, add the contents of your shutdown script.
  5. Continue with the VM creation process.

gcloud

Using the Google Cloud CLI, use the--metadata flag to providethe contents of your shutdown script, followed by theshutdown-script=CONTENTS key pair, whereCONTENTS is the content of yourshutdown script.

gcloud compute instances create example-instance --metadata shutdown-script="#! /bin/bash> # Shuts down Apache server> /etc/init.d/apache2 stop"

Terraform

To specify a shutdown script directly, use thegoogle_compute_instanceresource with the shutdown script in the metadata.

resource "google_compute_instance" "default" {  name         = "instance-name-shutdown-content-directly"  machine_type = "f1-micro"  zone         = "us-central1-c"  metadata = {    # Shuts down Apache server    shutdown-script = "#! /bin/bash /etc/init.d/apache2 stop"  }  boot_disk {    initialize_params {      image = "debian-cloud/debian-11"    }  }  network_interface {    # A default network is created for all Google Cloud projects    network = "default"    access_config {    }  }}

REST

In the API, provide a shutdown script as part of the metadata property inyour request when you create an instance. Useshutdown-script as themetadata key:

POST https://compute.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/instances{...  "metadata": {    "items": [      {       "key": "shutdown-script",       "value": "#! /bin/bash\n\n# Shuts down Apache server\n/etc/init.d/apache2 stop"      }    ]  }...}

Provide a shutdown script on Windows instances

Run shutdown scripts on Windows instances using the following Windows-specificmetadata keys. Choose from any of the specialized keys listed below.Each key should match the type of script you want to run.

You can specify multiple shutdown scripts by passing in different keys to yourinstance but each key can only be specified once per virtual machine.

The following keys can be used with a local shutdown script, using thesame instructionsearlier in this document.

cmd shutdown scriptsbat shutdown scriptsps1 shutdown scripts
windows-shutdown-script-cmdwindows-shutdown-script-batwindows-shutdown-script-ps1

Use a shutdown script from Cloud Storage

You can store and use a shutdown script from Cloud Storage. Followthe instructions in theStartup scriptsdocumentation but replacestartup-script-url withshutdown-script-url.

For Windows instances, replacewindows-startup-script-url withwindows-shutdown-script-url.

Apply a shutdown script to running instances

To add a shutdown script to a running instance, follow the instructions in theApplying a startup script to running instancesdocumentation but replace the metadata keys with one of the following keys:

  • shutdown-script: Supply the shutdown script contents directly withthis key. Using the Google Cloud CLI, you can provide the path to a shutdown scriptfile, using the--metadata-from-file flag and theshutdown-scriptmetadata key.
  • shutdown-script-url: Supply a Cloud Storage URL to theshutdown script file with this key.

Viewing the output of a shutdown script

Linux

You can view the output from a Linux shutdown script by doing any of thefollowing:

Windows

View the output from a Windows Server shutdown script by using any of thefollowing and checking forGCEMetadataScripts events:

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.