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.DeleteVpnGateway傳入參數ec2.DeleteVpnGatewayInput來刪除Virtual private gateway。

DeleteVpnGateway.VpnGatewayId填入要刪除的Virutal private gateway的ID。

main.go

package main

import (
    "context"

    "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.DeleteVpnGatewayInput{
        VpnGatewayId: &vpnGatewayId,
    }

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

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應用程式後在AWS console檢視Virtual private gateway已刪除。




沒有留言:

AdSense