Go以Google API Client Libraries來建立CloudWatch dashboard。
事前要求
參考「Golang 建立AWS CloudWatch API client」建立CloudWatch API client。
建立Dashbaord
呼叫cloudwatch.Client.PutDashboard
,傳入cloudwatch.PutDashboardInput
參數建立dashboard。
cloudwatch.PutDashboardInput
欄位如下:
DashboardName
- 填入dashboard的名稱。DashboardBody
- 填入dashboard的widgets設定,為JSON格式,參考Dashboard Body Structure and Syntax。
main.go
package main
import (
"context"
"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"
)
func main() {
ctx := context.TODO()
client := NewCloudWatchClient(ctx)
dashboardName := "cloudwatch-1"
dashboardBody := `
{
"widgets": []
}
`
_, err := client.PutDashboard(ctx, &cloudwatch.PutDashboardInput{
DashboardName: aws.String(dashboardName),
DashboardBody: aws.String(dashboardBody),
})
if err != nil {
panic(err)
}
}
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 a CloudWatch service client
}
測試
執行Go應用程式,前往AWS console可看到建立的CloudWatch dashboard。
沒有留言:
張貼留言