You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取GCP实例停止时间并实现脚本化快照迁移?

Got it, let's tackle this problem step by step. You want to grab the exact timestamp when a GCP VM instance entered the STOPPED state, then use that info to support server migration via snapshots. Here are two reliable methods to get that data:

Using gcloud CLI

This is the quickest way if you prefer command-line tools. GCP's gcloud CLI lets you query an instance's status history directly, which includes timestamps for every state change.

Run this command, replacing INSTANCE_NAME and INSTANCE_ZONE with your instance's details:

gcloud compute instances describe INSTANCE_NAME --zone=INSTANCE_ZONE --format="value(statusHistory[?status=='TERMINATED'].timestamp)" | sort -r | head -n1

What this does:

  • statusHistory is a field that tracks all state changes for the instance (like starting, stopping, restarting)
  • We filter for entries where the status is TERMINATED (this is the internal GCP status corresponding to a stopped instance)
  • sort -r orders the timestamps from newest to oldest, and head -n1 grabs the most recent one
Using Python with Google Cloud APIs

If you need to integrate this into an automation script (like for your migration workflow), using the official Google Cloud Compute Python client is the way to go.

Step 1: Set up dependencies

First, install the required library:

pip install google-cloud-compute

Make sure you're authenticated either via setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to your service account key file, or by running gcloud auth application-default login (for local development).

Step 2: The script

Here's a complete script that fetches the last stop time and formats it for readability:

from google.cloud import compute_v1
from datetime import datetime

def get_last_instance_stop_time(instance_name: str, zone: str, project_id: str):
    # Initialize the Compute Engine client
    instance_client = compute_v1.InstancesClient()
    
    # Fetch the instance details
    instance = instance_client.get(project=project_id, zone=zone, instance=instance_name)
    
    # Filter only TERMINATED state events from the status history
    terminated_events = [
        event for event in instance.status_history 
        if event.status == compute_v1.Instance.Status.TERMINATED
    ]
    
    if not terminated_events:
        return "This instance has never been stopped before."
    
    # Sort events to get the most recent stop first
    terminated_events.sort(key=lambda x: x.timestamp, reverse=True)
    latest_stop_timestamp = terminated_events[0].timestamp
    
    # Convert the raw ISO timestamp to a human-readable format (optional)
    readable_time = datetime.fromisoformat(latest_stop_timestamp.replace("Z", "+00:00")).strftime("%Y-%m-%d %H:%M:%S UTC")
    
    return f"Last stop time (UTC): {readable_time}\nRaw timestamp: {latest_stop_timestamp}"

if __name__ == "__main__":
    # Replace these values with your own
    YOUR_PROJECT_ID = "your-gcp-project-id"
    YOUR_INSTANCE_NAME = "target-vm-instance"
    YOUR_INSTANCE_ZONE = "us-central1-a"
    
    print(get_last_instance_stop_time(YOUR_INSTANCE_NAME, YOUR_INSTANCE_ZONE, YOUR_PROJECT_ID))

Notes for your migration workflow:

  • Ensure your service account or user has the Compute Viewer role (or higher) to access instance status history
  • Once you have the stop timestamp, you can use it to name snapshots (e.g., snapshot-2024-05-20-14-30) or validate that snapshots were created after the instance was stopped (critical for consistent migration)
  • If the instance is currently running, this will still return the last time it was stopped in the past

内容的提问来源于stack exchange,提问作者shrey tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:14:23