AdSense

網頁

2023/2/7

Golang 關聯AWS Direct Connect gateway與Virtual private gateway

Go以AWS提供的SDK aws-sdk-go-v2來關聯Direct Connect gateway與Virtual private gateway。



事前要求

參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。

參考「Golang 建立AWS Direct Connect gateway」建立Direct Connect gateway。

參考「Golang AWS VPC 附加Virtual private gateway」建立Virtual private gateway並附加於VPC。


關聯Direct Connect gateway與Virtual private gateway

呼叫directconnect.Client.CreateDirectConnectGatewayAssociation傳入參數directconnect.CreateDirectConnectGatewayAssociationInput來建立Direct Connect gateway與Virtual private gateway的關聯。

directconnect.CreateDirectConnectGatewayAssociationInput.DirectConnectGatewayId填入Direct Connect gateway的ID。

directconnect.CreateDirectConnectGatewayAssociationInput.VirtualGatewayId填入Virtual private gateway的ID。

main.go

package main

import (
    "context"
    "fmt"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/directconnect"
)

func main() {
    ctx := context.TODO()
    client := NewDirectConnectClient(ctx)

    directConnectGatewayId := "e44e0dfb-82b9-4e4f-bcc1-9d196f25d0af"
    virtualGatewayId := "vgw-0670c529abefaee33"
    params := &directconnect.CreateDirectConnectGatewayAssociationInput{
        DirectConnectGatewayId: &directConnectGatewayId,
        VirtualGatewayId:       &virtualGatewayId,
    }

    output, err := client.CreateDirectConnectGatewayAssociation(ctx, params)
    if err != nil {
        panic(err)
    }

    fmt.Println(*output.DirectConnectGatewayAssociation.AssociationId)   // 047dd041-3388-4907-a1df-f61de4644c0b
    fmt.Println(output.DirectConnectGatewayAssociation.AssociationState) // associating
    for _, prefix := range output.DirectConnectGatewayAssociation.AllowedPrefixesToDirectConnectGateway {
        fmt.Println(*prefix.Cidr)
    }
}

func NewDirectConnectClient(ctx context.Context) *directconnect.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-northeast-1"),
    )
    if err != nil {
        panic(err)
    }

    return directconnect.NewFromConfig(cfg) // Create an Amazon Direct Connect service client
}

github


測試

執行Go應用程式輸出以下結果。

047dd041-3388-4907-a1df-f61de4644c0b
associating
172.32.0.0/16
172.34.0.0/16
172.31.0.0/16
172.33.0.0/16

在AWS console檢視的Direct Connect gateway已關聯Virtual private gateway。




沒有留言:

AdSense