Go以Google API Client Libraries來取得EBS Volume metric統計資料。
事前要求
參考「Golang 取得AWS CloudWatch metric統計資料」。
取得EBS metric統計資料
呼叫cloudwatch.Client.GetMetricStatistics
,傳入cloudwatch.GetMetricStatisticsInput
參數來取得EBS metric統計資料。
cloudwatch.GetMetricStatisticsInput
欄位如下:
MetricName
- 填入指標(metric)名稱VolumeReadBytes
。StartTime
- 統計起始時間,這邊為目前時間前1小時。EndTime
- 統計結束時間,這邊為目前時間。Period
- 這邊為600
即為600秒,也就是每10分鐘統計一次。NamceSpace
- Metrics命名空間名稱AWS/EBS
。Statistics
- 統計指標,這裡為Sum
,即period區間總和。Dimensions
- 這邊要查循的維度為VolumeId
,值為EBS的[Volume ID]。
main.go
package main
import (
"context"
"fmt"
"sort"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
)
func main() {
ctx := context.TODO()
client := NewCloudWatchClient(ctx)
output, err := client.GetMetricStatistics(ctx, &cloudwatch.GetMetricStatisticsInput{
MetricName: aws.String("VolumeReadBytes"),
StartTime: aws.Time(time.Now().Add(-time.Hour * 1)),
EndTime: aws.Time(time.Now()),
Period: aws.Int32(600),
Namespace: aws.String("AWS/EBS"),
Statistics: []types.Statistic{types.StatisticSum},
Dimensions: []types.Dimension{
{
Name: aws.String("VolumeId"),
Value: aws.String("vol-02a899c6436c371a5"),
},
},
})
if err != nil {
panic(err)
}
dataPoints := output.Datapoints
sort.Slice(dataPoints, func(i, j int) bool {
return dataPoints[i].Timestamp.Before(*dataPoints[j].Timestamp)
})
for _, point := range output.Datapoints {
fmt.Println(*point.Timestamp)
fmt.Println(*point.Sum)
fmt.Println(point.Unit)
fmt.Println("========================================")
}
}
func NewCloudWatchClient(ctx context.Context) *cloudwatch.Client {
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion("ap-northeast-1"),
)
if err != nil {
panic(err)
}
return cloudwatch.NewFromConfig(cfg) // Create an Amazon CloudWatch service client
}
測試
執行Go應用程式印出以下。
2024-03-18 05:05:00 +0000 UTC
1.41999616e+08
Bytes
========================================
2024-03-18 05:15:00 +0000 UTC
1.75415296e+08
Bytes
========================================
2024-03-18 05:25:00 +0000 UTC
3.97312e+06
Bytes
========================================
沒有留言:
張貼留言