Go以Google API Client Libraries來建立GCP VPC network的private service connection連線到service producer。
事前要求
參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。
參考「Golang 建立GCP VPC network private service connection IP allocated range」建立VPC network的allocated IP range。
建立private connection to service連線
呼叫servicenetworking.NewService
取得servicenetworking.APIService
,接著呼叫servicenetworking.NewServicesConnectionsService
取得servicenetworking.ServicesConnectionsService
。
呼叫servicenetworkingte.ServiceConnectionService.Create
輸入參數parent
值為要連線的service,Google service固定為services/servicenetworking.googleapis.com
及參數servicenetworking.Connection
來建立連線。
servicenetworking.Connection
參數屬性如下:
servicenetworking.Connection.Network
- 填入VPC的SelfLink。servicenetworking.Connection.ReservedPeeringRanges
- 填入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)
parent := "services/servicenetworking.googleapis.com" // For Google services that support this functionality, this value is `services/servicenetworking.googleapis.com`.
vpcNetworkSelfLink := "projects/project-id-1/global/networks/demo-vpc-002" // vpc's selflink
reservedPeeringRangeName := "demo-vpc-002-allocated-range-001" // allocated IP range name
connection := &servicenetworking.Connection{
Network: vpcNetworkSelfLink,
ReservedPeeringRanges: []string{reservedPeeringRangeName},
}
call := serviceConnectionService.Create(parent, connection)
_, err = call.Do()
if err != nil {
panic(err)
}
}
測試
執行Go應用程式後,在GCP console查看建立的private connection to service如下。
沒有留言:
張貼留言