AdSense

網頁

2023/2/10

Golang 取得GCP Compute VM instance

Go以Google API Client Libraries來取得GCP Compute VM instance。



事前要求

參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。


下載API modules

在專案根目錄執行以下命令下載需要的google-api-go-client modules。



取得VM instance

呼叫compute.InstancesService.Get輸入project id、zone、instance名稱參數取得compute.Instance

main.go

package main

import (
    "context"
    "fmt"

    compute "google.golang.org/api/compute/v1"
)

func main() {
    ctx := context.Background()
    service, err := compute.NewService(ctx)
    if err != nil {
        panic(err)
    }
    instancesService := compute.NewInstancesService(service)

    projectId := "project-id-1"
    zone := "asia-east1-b"
    instanceName := "demo-instance"
    call := instancesService.Get(projectId, zone, instanceName)

    instance, err := call.Do()
    if err != nil {
        panic(err)
    }

    fmt.Println(instance.Id)                    // 6192712587621936341
    fmt.Println(instance.Name)                  // demo-instance
    fmt.Println(instance.MachineType)           // https://www.googleapis.com/compute/beta/projects/project-id-1/zones/asia-east1-b/machineTypes/e2-micro
    fmt.Println(instance.Disks[0].DiskSizeGb)   // 20
    fmt.Println(instance.Disks[0].DeviceName)   // demo-instance
    fmt.Println(instance.Disks[0].Architecture) // X86_64
    fmt.Println(instance.Disks[0].Boot)         // true
}

github


測試

執行Go應用程式輸出以下結果。

6192712587621936341
demo-instance
https://www.googleapis.com/compute/beta/projects/project-id-1/zones/asia-east1-b/machineTypes/e2-micro
20
demo-instance
X86_64
true

在GCP console查看此instance。




沒有留言:

AdSense