LoginSignup
6
4

More than 5 years have passed since last update.

AWS SDK for Go の CloudWatch を使ってみる

Posted at

AWS SDK for Go

AWS SDK for GoのCloudWatchドキュメント
にあるサンプルコードをコピペしてもママでは動かなかったので、その時の修正メモ。

go1.6 darwin/amd64 and the latest AWS GO SDK tagged as v1.1.31

AWS CloudWatchの設定

EC2インスタンスを一つ起動し、CloudWatchから以下の設定をしておいてください。

  • メトリックス CPUUtilization

Screen Shot 2016-05-29 at 9.52.12 PM.png

コードです

charge.go
package main

import (
    "fmt"
    "github.com/aws/aws-sdk-go/service/cloudwatch"
    "time"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
)

func main() {

    svc := cloudwatch.New(session.New(), &aws.Config{Region: aws.String("us-east-1")})

    params := &cloudwatch.GetMetricStatisticsInput{
        EndTime:    aws.Time(time.Now()),     // Required
        MetricName: aws.String("CPUUtilization"), // Required
        Namespace:  aws.String("AWS/EC2"),  // Required
        Period:     aws.Int64(60),             // Required
        StartTime:  aws.Time(time.Now().Add(time.Duration(24) * time.Hour * -1)),
        Statistics: []*string{ // Required
            aws.String(cloudwatch.StatisticMaximum), // Required
            // More values...
        },
        Dimensions: []*cloudwatch.Dimension{
            { // Required
                Name:  aws.String("InstanceId"),  // Required
                Value: aws.String("i-4b8f48d7"), // Required
            },
            // More values...
        },
        Unit: aws.String(cloudwatch.StandardUnitPercent),
    }

    resp, err := svc.GetMetricStatistics(params)

    if err != nil {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
        return
    }

    // Pretty-print the response data.
    fmt.Println(resp)

}

実行結果

Screen Shot 2016-05-30 at 9.41.33 AM.png

AWSコマンドならこんな感じ

aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start-time 2016-05-29T23:18:00 --end-time 2016-05-30T23:18:00 --period 60 --namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=i-4b8f48d7

説明

GetMetricStatisticsInput タイプのプロパティを以下のように指定します。

プロパティ 説明
StartTime 取得するデータの開始日(時間)
EndTime 取得するデータの終了日(時間)
MetricName メトリックス。例ではCPUの使用率。
Namespace 例ではEC2インスタンス
Unit データの単位。例ではパーセント
Dimensions サンプリング対象のEC2インスタンスID
Period サンプリングの粒度。例では60秒ごとに丸める。
Statistics Periodで指定した期間のデータをどのように集約するか。例では最大値。

プロパティの詳細はアマゾンのマニュアルをご覧ください。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4