Go以Google Cloud Client Libraries for Go來建立Private Cloud NAT。
範例環境:
- Go 1.19
- cloud.google.com/go/compute v1.27.0
事前要求
參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。
下載modules
在專案根目錄執行以下命令下載需要的API modules。
go get cloud.google.com/go/compute
建立Private NAT
GCP建立NAT需要先建立好Cloud Router並與之關聯。
呼叫compute.NewRoutersRESTClient
建立compute.RoutersClient
。
呼叫compute.RoutersClient.Insert
建立Cloud Router及NAT,傳入computepb.InsertRouterRequest
參數。
computepb.InsertRouterRequest
欄位如下:
Project
- Project IDRegion
- Router的區域ID,例如asia-east2
。RouterResource
- Router參數computepb.Router
欄位如下:Name
- Router名稱Network
- Router所屬的VPC Network。Nats
- Router的NAT清單,參數computepb.RouterNat
如下:Name
- NAT名稱SourceSubnetworkIpRangesToNat
- 允許連到NAT的子網路IP範圍。Type
- NAT類型,填入私有PRIVATE
main.go
package main
import (
"context"
compute "cloud.google.com/go/compute/apiv1"
"cloud.google.com/go/compute/apiv1/computepb"
)
func main() {
ctx := context.Background()
client, err := compute.NewRoutersRESTClient(ctx)
if err != nil {
panic(err)
}
routerName := "router1"
network := "projects/[PROJECT_ID]/global/networks/vpc1"
natName := "nat1"
allSubnetWorksAllPrimaryIpRanges := "ALL_SUBNETWORKS_ALL_IP_RANGES"
natType := "PRIVATE"
_, err = client.Insert(ctx, &computepb.InsertRouterRequest{
Project: "[PROJECT_ID]",
Region: "asia-east2",
RouterResource: &computepb.Router{
Name: &routerName,
Network: &network,
Nats: []*computepb.RouterNat{
{
Name: &natName,
SourceSubnetworkIpRangesToNat: &allSubnetWorksAllPrimaryIpRanges,
Type: &natType,
},
},
},
})
if err != nil {
panic(err)
}
}
沒有留言:
張貼留言