網頁

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」建立VPC network。


建立private service connection IP allocated range

呼叫compute.GlobalAddressesService.Insert輸入project id、compute.Address參數來建立VPC的allocated IP range。

compute.Address參數屬性如下:

  • compute.Address.Name - allocated IP range的名稱。
  • compute.Address.Region - 填入"GLOBAL"。
  • compute.Address.Network - 所屬VPC網路URL。
  • compute.Address.Address - IP位址,不填則由GCP自動分配。
  • compute.Address.PrefixLength - IP range prefix。
  • compute.Address.AddressType - 填入"INTERNAL"。
  • compute.Address.Purpose - 填入"VPC_PEERING"。

main.go

package main

import (
    "context"

    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"
    address := &compute.Address{
        Name:         "demo-vpc-002-private-service-allocated-ip-range-002",
        IpVersion:    "IPV4",
        Region:       "GLOBAL",
        Network:      "projects/project-id-1/global/networks/demo-vpc-002",
        Address:      "10.0.0.0",
        PrefixLength: int64(24),
        AddressType:  "INTERNAL",
        Purpose:      "VPC_PEERING",
    }
    call := globalAddressesService.Insert(projectId, address)

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

}

github


測試

執行Go應用程式後,在GCP console查看VPC分配的private service connection的allocated IP range如下。




沒有留言:

張貼留言