網頁

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與Virtual private gateway」建立Direct Connect gateway與Virtual private gateway關聯。


取得Direct Connect gateway與Virtual private gateway關聯

呼叫directconnect.Client.DescribeDirectConnectGatewayAssociations傳入參數directconnect.DescribeDirectConnectGatewayAssociationsInput來取得Direct Connect gateway與Virtual private gateway的關聯。

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

directconnect.DescribeDirectConnectGatewayAssociationsInput.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.DescribeDirectConnectGatewayAssociationsInput{
        DirectConnectGatewayId: &directConnectGatewayId,
        VirtualGatewayId:       &virtualGatewayId,
    }

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

    fmt.Println(*output.DirectConnectGatewayAssociations[0].AssociationId)   // 047dd041-3388-4907-a1df-f61de4644c0b
    fmt.Println(output.DirectConnectGatewayAssociations[0].AssociationState) // associated
    for _, prefix := range output.DirectConnectGatewayAssociations[0].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
associated
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。




沒有留言:

張貼留言