如何获取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:
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:
statusHistoryis 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 -rorders the timestamps from newest to oldest, andhead -n1grabs the most recent one
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

