# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # CloudWatch Custom Widget sample: snapshot CloudWatch metric graphs in dashboard to S3 import base64 import boto3 import datetime import json import os import secrets DOCS = """## Store bitmap snapshot of a CloudWatch Dashboard in S3 Stores bitmap snapshots of all metric widgets in the current CloudWatch Dashboard and in a HTML file in S3.""" CSS = "" def load_dashboard(dashboardName): cloudwatch = boto3.client('cloudwatch') dashboard = cloudwatch.get_dashboard(DashboardName=dashboardName) return json.loads(dashboard['DashboardBody']) def get_metric_bitmaps(widgets, start, end, unitWidth, unitHeight): bitmaps = [] for widget in widgets: if widget['type'] != 'metric': continue width = widget['width'] if 'width' in widget else 12 height = widget['height'] if 'height' in widget else 12 widgetProps = widget['properties'] graph = { **widgetProps, 'start': start, 'end': end, 'width': int(width * unitWidth), 'height': int(height * unitHeight) } params = { 'MetricWidget': json.dumps(graph) } region = widgetProps['region'] cloudwatch = boto3.client('cloudwatch', region_name=region) image = cloudwatch.get_metric_widget_image(**params) bitmaps.append(image['MetricWidgetImage']) return bitmaps def get_snapshot_html(dashboardName, bitmaps): subject = f"Dashboard snapshot: {dashboardName}" html = f"
Snapshot uploaded successfully to {s3Path}
Snapshot failed to upload to '{s3Path}': {e}" else: msg = "
s3Bucket parameter not set, please set by editing widget and entering an S3 bucket that exists in this account" return f"""{CSS}{msg}"""