Skip to main content

CloudWatch

You can use the AWS Command Line Interface (CLI) to generate a PNG image of a metric graph from Amazon CloudWatch using the get-metric-widget-image command. This command allows you to specify a CloudWatch Metric Widget JSON definition and then retrieve the corresponding image in PNG format.

Look for valid values using

aws cloudwatch list-metrics --query "Metrics[].Namespace" --output text | sort | uniq

Filter down to a specific unit

aws cloudwatch list-metrics --namespace "AWS/EC2" --dimensions Name=InstanceId,Value=i-0123456789abcdef0

or something like

$ aws cloudwatch list-metrics \
--namespace "AWS/S3" \
--dimensions Name=BucketName,Value=mybucket

which returns

{
"Metrics": [
{
"Namespace": "AWS/S3",
"MetricName": "BucketSizeBytes",
"Dimensions": [
{
"Name": "BucketName",
"Value": "mybucket"
},
{
"Name": "StorageType",
"Value": "StandardStorage"
}
]
},
{
"Namespace": "AWS/S3",
"MetricName": "NumberOfObjects",
"Dimensions": [
{
"Name": "BucketName",
"Value": "mybucket"
},
{
"Name": "StorageType",
"Value": "AllStorageTypes"
}
]
}
]
}

Now you can have a metrics set that looks like this:

{
"metrics": [
[ "AWS/S3", "NumberOfObjects", "BucketName", "mybucket" ]
],
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "Bucket Size"
}

and then execute as

aws cloudwatch get-metric-widget-image --metric-widget '{
"width": 600,
"height": 400,
"metrics": [
[ "AWS/S3", "NumberOfObjects", "BucketName", "mybucket" ]
],
"period": 300,
"stat": "Average",
"region": "us-east-1",
"title": "Bucket Size",
"view": "timeSeries",
"start": "-PT1H",
"end": "PT0H",
"stacked": false,
"yAxis": {"left": {"min": 0, "max": 100}}
}' --output-format json | jq -r '.MetricWidgetImage' | base64 --decode > widget_image.png

The last part with jq and base64 is important if calling from the AWS CLI, but will be different for calling directly as an API endpoint.