AdSense

網頁

2024/6/7

Golang 建立GCP Private Cloud NAT

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。



建立Private NAT

GCP建立NAT需要先建立好Cloud Router並與之關聯。

呼叫compute.NewRoutersRESTClient建立compute.RoutersClient

呼叫compute.RoutersClient.Insert建立Cloud Router及NAT,傳入computepb.InsertRouterRequest參數。

computepb.InsertRouterRequest欄位如下:

  • Project - Project ID
  • Region - 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)
    }

}

github


沒有留言:

AdSense