AdSense

網頁

2023/2/8

Golang 取得AWS VPC Virtual private gateway

Go以AWS提供的SDK aws-sdk-go-v2來取得Virtual private gateway。



事前要求

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

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


取得Virtual private gateway

呼叫ec2.Client.DescribeVpnGateways傳入參數ec2.DescribeVpnGatewaysInput來取得Virtual private gateway資料。

DescribeVpnGatewaysInput.VpnGatewayIds填入要取得的Virutal private gateway的ID。

ec2.Client.DescribeVpnGateways回傳的DescribeVpnGatewaysOutput.VpcAttachments[].VpcAttachments[].VpcId可取得附加的VPC ID。

main.go

package main

import (
    "context"
    "fmt"

    "github.com/aws/aws-sdk-go-v2/config"

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

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

    vpnGatewayId := "vgw-0670c529abefaee33"
    params := &ec2.DescribeVpnGatewaysInput{
        VpnGatewayIds: []string{vpnGatewayId},
    }

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

    fmt.Println(*output.VpnGateways[0].VpcAttachments[0].VpcId) // vpc-0e6e56e06a48ef314
}

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

    return ec2.NewFromConfig(cfg) // Create an Amazon EC2 service client
}

github


測試

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

vpc-0e6e56e06a48ef314

在AWS console檢視取得的Virtual private gateway。




沒有留言:

AdSense