AdSense

網頁

2024/3/5

Golang 建立AWS CloudWatch Dashboard

Go以Google API Client Libraries來建立CloudWatch dashboard。


事前要求

參考「Golang 建立AWS CloudWatch API client」建立CloudWatch API client。



建立Dashbaord

呼叫cloudwatch.Client.PutDashboard,傳入cloudwatch.PutDashboardInput參數建立dashboard。

cloudwatch.PutDashboardInput欄位如下:



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
}

github



測試

執行Go應用程式,前往AWS console可看到建立的CloudWatch dashboard。




沒有留言:

AdSense