boto equivalent of aws client command

84 Views Asked by At

I have this command that works as expected. But I will like to use boto instead.

aws cloudwatch get-metric-statistics \
    --region ap-south-1 \
    --namespace AWS/RDS \
    --metric-name DBLoad  \
    --period 60 \
    --statistics Average \
    --start-time 2023-06-12T21:00:00Z \
    --end-time 2023-06-12T23:59:00Z \
    --dimensions Name=DBInstanceIdentifier,Value=sql-rds

Does boto support all the parameters?

2

There are 2 best solutions below

1
djmonki On BEST ANSWER

The AWS CloudWatch functionality, including the get_metric_statistics operation, is available in Boto3

See here: Boto3 documentation - CloudWatch Client - get_metric_statistics

Using Boto3 - the code would be :

import boto3
from datetime import datetime, timedelta

client = boto3.client('cloudwatch', region_name='ap-south-1')

response = client.get_metric_statistics(
    Namespace='AWS/RDS',
    MetricName='DBLoad',
    Dimensions=[
        {
            'Name': 'DBInstanceIdentifier',
            'Value': 'sql-rds'
        },
    ],
    StartTime=datetime(2023, 6, 12, 21, 0, 0),
    EndTime=datetime(2023, 6, 12, 23, 59, 0),
    Period=60,
    Statistics=['Average']
)

print(response)

N.B.
Boto is no longer officially maintained by AWS
Boto documentation might not be up-to-date
It does not provide the same level of support for AWS services as Boto3.

However, if you need to use Boto the documentation is here: boto.ec2.cloudwatch

Using Boto - the code would be :

import boto

conn = boto.connect_cloudwatch()
region = 'ap-south-1'

namespace = 'AWS/RDS'
metric_name = 'DBLoad'
dimensions = {'DBInstanceIdentifier': 'sql-rds'}

start_time = '2023-06-12T21:00:00Z'
end_time = '2023-06-12T23:59:00Z'

period = 60
statistics = ['Average']

response = conn.get_metric_statistics(
    period=period,
    start_time=start_time,
    end_time=end_time,
    metric_name=metric_name,
    namespace=namespace,
    statistics=statistics,
    dimensions=dimensions,
    region=region
)

print(response)
0
Shloka Bhalgat On

You can do it this way using boto3-

import boto3
import matplotlib.pyplot as plt
from tabulate import tabulate
from unskript.enums.aws_k8s_enums import StatisticsType
from datetime import datetime, timedelta

timestamps = []
values = []
cloudwatchClient = boto3.client('cloudwatch', region_name='ap-south-1')
start_time = datetime(2023, 6, 12, 21, 0, 0)
end_time = datetime(2023, 6, 12, 23, 59, 0)
dimensions = [{'Name': 'name-1', ... }]
metric_name = 'DBLoad' # in your case
period = 60 #The granularity, in seconds, of the returned data points.
statistics = ['Average'] #in your case

res = cloudwatchClient.get_metric_data(
      MetricDataQueries=[
        {
            'Id': metric_name.lower(),
            'MetricStat': {
                'Metric': {
                    'Namespace': 'AWS/RDS',
                    'MetricName': metric_name,
                    'Dimensions': dimensions
                },
                'Period': period,
                'Stat': statistics,
            },
        },
    ],
    StartTime= start_time,
    EndTime=end_time,
    ScanBy='TimestampAscending'
)

for timestamp in res['MetricDataResults'][0]['Timestamps']:
    timestamps.append(timestamp)
for value in res['MetricDataResults'][0]['Values']:
    values.append(value)

timestamps.sort()
values.sort()

plt.plot_date(timestamps, values, "-o")

data = []
for dt, val in zip(
    res['MetricDataResults'][0]['Timestamps'],
    res['MetricDataResults'][0]['Values']
    ):
    data.append([dt.strftime('%Y-%m-%d::%H-%M'), val])
head = ["Timestamp", "Value"]
table = tabulate(data, headers=head, tablefmt="grid")

print(table)