網頁

2023/2/7

Golang 建立AWS VPC Virtual private gateway

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



事前要求

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

參考「Golang 建立AWS VPC API client」建立VPC API client。


建立Virtual private gateway

呼叫ec2.Client.CreateVpnGateway傳入參數ec2.CreateVpnGatewayInput來建立virtual private gateway。

main.go

package main

import (
    "context"
    "fmt"

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

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

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

    amazonSideAsn := int64(64512)
    key := "Name"
    value := "demo-virtual-private-gateway-001"
    tag := types.Tag{
        Key:   &key,
        Value: &value,
    }
    tagSpecification := types.TagSpecification{
        ResourceType: types.ResourceTypeVpnGateway,
        Tags:         []types.Tag{tag},
    }
    params := &ec2.CreateVpnGatewayInput{
        Type:              types.GatewayTypeIpsec1,
        AmazonSideAsn:     &amazonSideAsn,
        TagSpecifications: []types.TagSpecification{tagSpecification},
    }

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

    vpg := output.VpnGateway
    fmt.Println(*vpg.VpnGatewayId) // vgw-0670c529abefaee33
}

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應用程式輸出以下結果。

vgw-0670c529abefaee33

在AWS console檢視建立的virtual private gateway。




沒有留言:

張貼留言