Go以AWS提供的SDK aws-sdk-go-v2來附加Virtual private gateway至VPC。
事前要求
參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。
參考「Golang 建立AWS VPC」建立VPC。
參考「Golang 建立AWS VPC Virtual private gateway」建立Virtual private gateway。
附加Virtual private gateway至VPC
呼叫ec2.Client.AttachVpnGateway傳入參數ec2.AttachVpnGatewayInput來附加virtual private gateway至VPC。
ec2.AttachVpnGatewayInput.VpcId填入VPC ID。
ec2.AttachVpnGatewayInput.VpnGatewayId填入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/ec2"
)
func main() {
ctx := context.TODO()
client := NewEC2Client(ctx)
vpcId := "vpc-0e6e56e06a48ef314"
vpnGatewayId := "vgw-0670c529abefaee33"
params := &ec2.AttachVpnGatewayInput{
VpcId: &vpcId,
VpnGatewayId: &vpnGatewayId,
}
output, err := client.AttachVpnGateway(ctx, params)
if err != nil {
panic(err)
}
fmt.Println(*output.VpcAttachment.VpcId) // vpc-0e6e56e06a48ef314
fmt.Println(output.VpcAttachment.State) // attaching
}
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
}
測試
執行Go應用程式輸出以下結果。
vpc-0e6e56e06a48ef314
attaching
在AWS console檢視virtual private gateway已附加至VPC。
沒有留言:
張貼留言