0

Switch Instance Boot Status

by
Published Jul 17, 2024

Switch a virtual machine instance boot status to start or stop it. [See the documentation](https://cloud.google.com/compute/docs/instances/stop-start-instance)

Script gcloud Verified

The script

Submitted by hugo697 Bun
Verified 692 days ago
1
import { InstancesClient, ZoneOperationsClient } from "@google-cloud/compute";
2

3
type Gcloud = {
4
  type: string;
5
  project_id: string;
6
  private_key_id: string;
7
  private_key: string;
8
  client_email: string;
9
  client_id: string;
10
  auth_uri: string;
11
  token_uri: string;
12
  auth_provider_x509_cert_url: string;
13
  client_x509_cert_url: string;
14
  universe_domain: string;
15
};
16

17
export async function main(
18
  resource: Gcloud,
19
  zone: string,
20
  instanceName: string,
21
  newInstanceStatus: "start" | "stop",
22
  waitCompletion: boolean = false
23
) {
24
  if (!["start", "stop"].includes(newInstanceStatus)) {
25
    throw new Error("The new VM boot status must be 'start' or 'stop'.");
26
  }
27

28
  const instancesClient = new InstancesClient({
29
    credentials: resource,
30
    projectId: resource.project_id,
31
  });
32

33
  const [response] = await instancesClient[newInstanceStatus]({
34
    project: resource.project_id,
35
    zone,
36
    instance: instanceName,
37
  });
38

39
  let operation: any = response.latestResponse;
40

41
  if (waitCompletion) {
42
    const operationsClient = new ZoneOperationsClient({
43
      credentials: resource,
44
      projectId: resource.project_id,
45
    });
46

47
    while (operation.status !== "DONE") {
48
      [operation] = await operationsClient.wait({
49
        operation: operation.name,
50
        project: resource.project_id,
51
        zone: operation.zone.split("/").pop(),
52
      });
53
    }
54
  }
55

56
  return operation;
57
}
58