Go以Google API Client Libraries來取得操作CloudWatch的API client。
事前要求
參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的credentials。
下載AWS SDK Go V2 modules
在專案根目錄執行以下命令下載需要的aws-sdk-go-v2 modules。
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/cloudwatch
建立CloudWatch API client
呼叫config.LoadDefaultConfig
傳入region參數(e.g. "ap-northeast-1"
)建立aws.Conifg
物件,AWS SDK預設會讀取$HOME/.aws/credentials
的access keys來通過權限驗證,然後呼叫cloudwatch.NewFromConfig
建立cloudwatch.Client
。
main.go
package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
)
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
}
func main() {
ctx := context.TODO()
client := NewCloudWatchClient(ctx)
...
}
沒有留言:
張貼留言