Go以AWS提供的SDK aws-sdk-go-v2來建立VPC Route table的route。
事前要求
參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。
參考「Golang 建立AWS VPC Route table」建立Route table。
參考「Golang 建立AWS VPC Internet gateway附加到VPC」建立Internet gateway。
建立Route
呼叫ec2.Client.CreateRoute傳入參數ec2.CreateRouteInput來建立Route table的route。
ec2.CreateRouteInput.RouteTableId填入Route table ID。
ec2.CreateRouteInput.DestinationCidrBlock填入Destination的CIDR block。
ec2.CreateRouteInput.GatewayId填入Target的gateway ID,這邊為internet 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)
routeTableId := "rtb-0b0e21c8e3b1cda13"
cidrBlock := "0.0.0.0/0"
internetGatewayId := "igw-0f611889b41740e85"
input := &ec2.CreateRouteInput{
RouteTableId: &routeTableId,
DestinationCidrBlock: &cidrBlock,
GatewayId: &internetGatewayId,
}
_, err := client.CreateRoute(ctx, input)
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
}
測試
執行Go應用程式。
在AWS console檢視Route table新增的route。
沒有留言:
張貼留言