網頁

2024/3/4

Golang 取得GCP機器映像 Get machine image

Go以Google API Client Libraries來取得機器映像(Machine image)。


事前要求

參考「Golang 建立GCP機器映像 Create machine image」建立machine image。


取得Machine image

呼叫compute.MachineImagesService.Get輸入project id,和參數machineImage(機器映像名稱)取得machine image。

main.go

package main

import (
    "context"
    "fmt"

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

func main() {
    ctx := context.Background()
    computeService, err := compute.NewService(ctx)
    if err != nil {
        panic(err)
    }
    projectId := "project-id-1"

    machineImagesService := compute.NewMachineImagesService(computeService)
    machineImage := "instance-1-image"
    call := machineImagesService.Get(projectId, machineImage)

    result, err := call.Do()
    if err != nil {
        panic(err)
    }
    fmt.Println(result.SelfLink)
    fmt.Println(result.SourceInstance)
    fmt.Println(result.TotalStorageBytes)

    for i, saveDisk := range result.SavedDisks {
        fmt.Printf("=====saveDisk[%d]=====\n", i)
        fmt.Println(saveDisk.SourceDisk)
        fmt.Println(saveDisk.StorageBytes)
    }

    for i, disk := range result.InstanceProperties.Disks {
        fmt.Printf("=====disk[%d]=====\n", i)
        fmt.Println(disk.Index)
        fmt.Println(disk.Boot)
        fmt.Println(disk.DeviceName)
        fmt.Println(disk.DiskSizeGb)
    }

}

github



測試

執行Go應用程式印出以下。

https://www.googleapis.com/compute/v1/projects/project-id-1/global/machineImages/instance-1-image
https://www.googleapis.com/compute/v1/projects/project-id-1/zones/asia-east2-b/instances/instance-1
672734080
=====saveDisk[0]=====
projects/project-id-1/zones/asia-east2-b/disks/instance-1
672734080
=====saveDisk[1]=====
projects/project-id-1/zones/asia-east2-b/disks/disk-1
0
=====disk[0]=====
0
true
instance-1
10
=====disk[1]=====
1
false
disk-1
10

沒有留言:

張貼留言