網頁

2023/4/20

Golang 取得GCP VPC network private service connection IP allocated range清單

Go以Google API Client Libraries來查詢GCP VPC network的private service connection的IP range列表。



事前要求

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

參考「Golang 建立GCP VPC network private service connection IP allocated range」建立VPC的allocated IP range。


查詢private service connection IP allocated range清單

呼叫compute.GlobalAddressesService.List輸入project id參數來取得全部的global IP位址清單,並依VPC SelfLink名稱篩選VPC的allocated IP range。

main.go

package main

import (
    "context"
    "fmt"
    "strings"

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

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

    globalAddressesService := compute.NewGlobalAddressesService(service)

    projectId := "project-id-1"
    call := globalAddressesService.List(projectId)

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

    vpcSelfLink := "projects/proejct-id-1/global/networks/demo-vpc-002"
    for _, item := range addressList.Items {
        if strings.Contains(item.Network, vpcSelfLink) {
            fmt.Println(item.Network)
            fmt.Println(item.Name)
            fmt.Printf("%s/%d\n", item.Address, item.PrefixLength)
        }
    }

}

github


測試

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

https://www.googleapis.com/compute/v1/projects/project-id-1/global/networks/demo-vpc-002
demo-vpc-002-allocated-range-001
192.168.0.0/24


沒有留言:

張貼留言