AdSense

網頁

2023/4/25

Golang GCP VPC network private service connection新增allocated IP range

Go以Google API Client Libraries來在GCP VPC network的private service connection連線加入新的allocated IP range。



事前要求

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

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

參考「Golang 建立GCP VPC network private service connection與service producer的連線」建立VPC private service connection。


Private connection新增allocated IP range

呼叫servicenetworking.NewService取得servicenetworking.APIService,接著呼叫servicenetworking.NewServicesConnectionsService取得servicenetworking.ServicesConnectionsService

呼叫compuservicenetworkingte.ServiceConnectionService.Patch輸入參數parent值為要連線的service connection名稱,Google service connection名稱固定為services/servicenetworking.googleapis.com/connections/servicenetworking-googleapis-com及參數servicenetworking.Connection來加入allocated IP range。

servicenetworking.Connection參數屬性如下:

  • servicenetworking.Connection.Network - 填入VPC的SelfLink。
  • servicenetworking.Connection.ReservedPeeringRanges - 填入allocated IP range的名稱,既有的allocated IP range名稱與新增的名稱都要填才能正確加入。

main.go

package main

import (
    "context"

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

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

    serviceConnectionService := servicenetworking.NewServicesConnectionsService(service)

    // For Google services that support this functionality, this is`services/servicenetworking.googleapis.com/connections/servicenetworking-googleapis-com`.
    serviceConnectionName := "services/servicenetworking.googleapis.com/connections/servicenetworking-googleapis-com"
    vpcNetworkSelfLink := "projects/project-id-1/global/networks/demo-vpc-002" // vpc's selflink
    existedReservedPeeringRangeName := "demo-vpc-002-allocated-range-001"      // assigned allocated IP range name
    newReservedPeeringRangeName := "demo-vpc-002-allocated-range-002"          // new allocated IP range name

    connection := &servicenetworking.Connection{
        Network: vpcNetworkSelfLink,
        ReservedPeeringRanges: []string{
            existedReservedPeeringRangeName,
            newReservedPeeringRangeName,
        },
    }

    call := serviceConnectionService.Patch(serviceConnectionName, connection)
    _, err = call.Do()
    if err != nil {
        panic(err)
    }

}

github


沒有留言:

AdSense