AdSense

網頁

2023/4/20

Golang 取得GCP VPC network

Go以Google API Client Libraries取得GCP VPC network



事前要求

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

參考「Golang 建立GCP VPC network」建立VPC network。


取得VPC network

呼叫compute.NetworksService.Get輸入project id、VPC名稱參數來取得VPC network。

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)
    }

    networksService := compute.NewNetworksService(service)

    projectId := "project-id-1"
    vpcName := "demo-vpc-002"
    call := networksService.Get(projectId, vpcName)

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

    fmt.Println(network.Name)             // demo-vpc-002
    fmt.Println(len(network.Subnetworks)) // 37
    fmt.Println(network.Subnetworks[0])   // https://www.googleapis.com/compute/v1/projects/project-id-1/regions/europe-west9/subnetworks/demo-vpc-002
}

github


測試

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

demo-vpc-002
37
https://www.googleapis.com/compute/v1/projects/project-id-1/regions/europe-west9/subnetworks/demo-vpc-002

沒有留言:

AdSense