Python: Boto3: get_metric_statistics() only accepts keyword argumentsAsk Question

问题:

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

回答1:


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).

回答2:


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)
标签: boto3 amazon-cloudwatch
© 2014 TuiCode, Inc.