網頁

2024/1/9

Golang 查詢GCP公用作業系統映像檔 Query public OS images

Go以Google API Client Libraries來查詢public OS Images。



事前要求

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


下載API modules

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



查詢Public OS Images

呼叫compute.ImagesService.List輸入project id取得OS images;public id輸入要查詢public OS images的image project名稱,例如Debian為debian-cloud。Image project請見Operating system details

範例使用compute.ImagesListCall.Filter來篩選查詢結果資料,(name:debian-12-*) AND (family:debian-12)代表只回傳name欄位名稱開頭為debian-12-family欄位值為debian-12的結果。

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 := "debian-cloud"

    imagesService := compute.NewImagesService(computeService)

    call := imagesService.List(projectId)
    imageList, err := call.
        Filter("(name:debian-12-*) AND (family:debian-12)").
        Do()
    if err != nil {
        panic(err)
    }

    for _, item := range imageList.Items {
        fmt.Println(item.Name)
        fmt.Println(item.SelfLink)
    }

}

github


測試

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

debian-12-bookworm-v20230609
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230609
debian-12-bookworm-v20230629
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230629
debian-12-bookworm-v20230711
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230711
debian-12-bookworm-v20230724
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230724
debian-12-bookworm-v20230809
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230809
debian-12-bookworm-v20230814
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230814
debian-12-bookworm-v20230912
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20230912
debian-12-bookworm-v20231004
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20231004
debian-12-bookworm-v20231010
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20231010
debian-12-bookworm-v20231113
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20231113
debian-12-bookworm-v20231115
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20231115
debian-12-bookworm-v20231212
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-12-bookworm-v20231212


沒有留言:

張貼留言