Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Boto3: get_metric_statistics() only accepts keyword arguments

Just started using Boto3 with Python so definitely new at this.

I'm trying to use a simple get_metric_statistics script to return information about CPUUtilization for an instance. Here is the script I'm looking to use:

import boto3
import datetime

cw = boto3.client('cloudwatch')

cw.get_metric_statistics(       
        300,
        datetime.datetime.utcnow() - datetime.timedelta(seconds=600),
        datetime.datetime.utcnow(),
        'CPUUtilization',
        'AWS/EC2',
        'Average',
        {'InstanceId':'i-11111111111'},
        )

but I keep getting the following message:

Traceback (most recent call last):
  File "C:..../CloudWatch_GetMetricStatistics.py", line 13, in <module>
    {'InstanceId':'i-0c996c11414476c7c'},
  File "C:\Program Files\Python27\lib\site-packages\botocore\client.py", line 251, in _api_call
    "%s() only accepts keyword arguments." % py_operation_name)
TypeError: get_metric_statistics() only accepts keyword arguments.

I have:

  1. Looked at the documentation on Boto3 and I believe I have got everything correctly written/included
  2. Set the correct region/output format/security credentials in the .aws folder
  3. Googled similar problems with put_metric_statistics, etc to try and figure it out

I'm still stuck as to what I'm missing?

Any guidance would be much appreciated.

Many thanks Ben

like image 959
user7925487 Avatar asked Apr 26 '17 12:04

user7925487


2 Answers

Refer to the documentation, and your error message:

get_metric_statistics() only accepts keyword agruments

Named arguments must be passed to the function as is defined in the docs:

get_metric_statistics(**kwargs)
like image 109
mickzer Avatar answered Nov 15 '22 15:11

mickzer


This works:

import boto3
import datetime

cw = boto3.client('cloudwatch')

cw.get_metric_statistics(
        Period=300,
        StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=600),
        EndTime=datetime.datetime.utcnow(),
        MetricName='CPUUtilization',
        Namespace='AWS/EC2',
        Statistics=['Average'],
        Dimensions=[{'Name':'InstanceId', 'Value':'i-abcd1234'}]
        )

To find the right values, I use the AWS Command-Line Interface (CLI):

aws cloudwatch list-metrics --namespace AWS/EC2 --metric-name CPUUtilization --max-items 1

It returns information such as:

{
    "Metrics": [
        {
            "Namespace": "AWS/EC2", 
            "Dimensions": [
                {
                    "Name": "InstanceId", 
                    "Value": "i-abcd1234"
                }
            ], 
            "MetricName": "CPUUtilization"
        }
    ], 
    "NextToken": "xxx"
}

You can then use these values to populate your get_metric_statistics() requet (such as the Dimensions parameter).

like image 21
John Rotenstein Avatar answered Nov 15 '22 13:11

John Rotenstein