7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「CloudWatchダッシュボードで期間指定するのがめんどくさい」を解消

Posted at

背景

前月の通信情報などをCloudWatchダッシュボードのスクリーンショットで取得したいという要望があったとします。複数のCloudWatchダッシュボードから前月の情報のスクリーンショットを取得する際、毎回手動で下記の箇所で期間を指定するのは非常に手間がかかります。特に複数のダッシュボードが存在する場合、この作業は結構大変です。

※一旦「過去の通信量を見るのではなく、ダッシュボードでリアルタイムで通信量を監視することが推奨されます」といった話はおいておいて。。。

report01.png

そこで、CloudWatchダッシュボードに移動した際に、デフォルトで前月の1日から最終日までのグラフが表示されるように自動化します。

report02.png

実装方法

レポート用のダッシュボード作成

CloudWatchダッシュボードは以下の手順でコピーできます。普段の監視用とは別に、全ての情報を統合したレポート用のダッシュボードを一つ作成します。

report03.png

下記手順で新しいダッシュボードを作成します。

  • 現在のダッシュボードに移動し、「アクション」→「ソースの表示/編集」をクリック
  • ダッシュボードの情報がJSON形式で表示される
  • 他の対象ダッシュボードでも同様にソースの表示を行い、表示された情報を結合して一つのJSONファイルを作成

report04.png

続いて、作成したレポート用ダッシュボード「report」に移動後、「アクション」→「ソースの表示/編集」をクリックして、作成したJSONファイルの情報を貼り付けます。この方法により、複数のダッシュボードの情報をコピーして一つのダッシュボードを作成することができます。

期間指定処理の設定について

CloudWatchダッシュボードの期間(下記の赤枠)を自動設定することはできませんが、各ウィジェット(下記青枠内)に時間指定の情報を持たせることができます。ウィジェットを選択後、「編集」をクリックします。

report05.png

「持続時間範囲」の箇所に前月の範囲を指定します。

report06.png

全てのウィジェットに手動でこの設定を行うことは逆に非効率となってしまいます。そこで、レポート用ダッシュボード「report」内のウィジェットについて、前月の範囲に更新するLambda関数を作成し、EventBridgeスケジューラから毎月1日に実行する設定を追加します。

Lambda関数の実装

以下のLambda関数を作成します。

import boto3
import json
from datetime import datetime, timedelta

def lambda_handler(event, context):
    dashboard_name = 'report'
    cloudwatch = boto3.client('cloudwatch')

    jst_offset = timedelta(hours=9)
    today = datetime.utcnow() + jst_offset
    first_this_month_jst = datetime(today.year, today.month, 1)
    first_last_month_jst = (first_this_month_jst - timedelta(days=1)).replace(day=1)
    last_last_month_jst = first_this_month_jst - timedelta(days=1)

    start_utc = first_last_month_jst - jst_offset
    end_utc = last_last_month_jst.replace(hour=23, minute=59, second=59) - jst_offset

    start_str = start_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
    end_str = end_utc.strftime('%Y-%m-%dT%H:%M:%SZ')

    response = cloudwatch.get_dashboard(DashboardName=dashboard_name)
    body = json.loads(response['DashboardBody'])

    for widget in body.get('widgets', []):
        props = widget.get('properties', {})
        props['start'] = start_str
        props['end'] = end_str

    cloudwatch.put_dashboard(
        DashboardName=dashboard_name,
        DashboardBody=json.dumps(body)
    )

    return {
        'statusCode': 200,
        'body': f"{dashboard_name} updated to JST {first_last_month_jst.date()} ~ {last_last_month_jst.date()}"
    }

Lambda関数の実行と確認

このLambda関数をEventBridgeから毎月自動実行することで、グラフの期間範囲が自動更新されます。今回はLambdaコンソールからテスト実行しています。テスト実行後、以下のような結果が出力されます。

{
  "statusCode": 200,
  "body": "report updated to JST 2025-06-01 ~ 2025-06-30"
}

ダッシュボードに移動すると、期間が正しく更新されていることが確認できます。

report02.png

まとめ

この手法により、CloudWatchダッシュボードの期間を自動的に前月の範囲に更新することができます。EventBridgeスケジューラと組み合わせることで、毎月1日に自動実行され、手動での期間設定作業が不要になります。

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?