Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boto3 - Print AWS Instance Average CPU Utilization

I am trying to print out just the averaged CPU utilization of an AWS instance. This code will print out the 'response' but the for loop at the end isn't printing the averaged utilization. Could someone assist? Thank you in advance!

    import boto3
    import sys
    from datetime import datetime, timedelta
        client = boto3.client('cloudwatch')
        response = client.get_metric_statistics(
            Namespace='AWS/EC2',
            MetricName='CPUUtilization',
            Dimensions=[
                {
                'Name': 'InstanceId',
                'Value': 'i-1234abcd'
                },
            ],
            StartTime=datetime(2018, 4, 23) - timedelta(seconds=600),
            EndTime=datetime(2018, 4, 24),
            Period=86400,
            Statistics=[
                'Average',
            ],
            Unit='Percent'
        )
    for cpu in response:
        if cpu['Key'] == 'Average':
            k = cpu['Value']
    print(k)

This is the error message I am getting:

    Traceback (most recent call last):
      File "C:\bin\TestCW-CPU.py", line 25, in <module>
        if cpu['Key'] == 'Average':
    TypeError: string indices must be integers
like image 430
jmoorhead Avatar asked Apr 26 '18 13:04

jmoorhead


People also ask

What is EC2 CPU utilization?

CPU utilization is the percentage of allocated EC2 compute units that are currently in use on the instance. This metric measures the percentage of allocated CPU cycles that are being utilized on an instance. The CPU Utilization CloudWatch metric shows CPU usage per instance and not CPU usage per core.

How do I find my EC2 instance details?

You can use EC2 Instance Metadata Query Tool which is a simple bash script that uses curl to query the EC2 instance Metadata from within a running EC2 instance as mentioned in documentation. now run command to get required data.


2 Answers

for cpu in response['Datapoints']:
  if 'Average' in cpu:
    print(cpu['Average'])

2.25348611111
2.26613194444

You can see why this works, if you print the value of cpu:

print(response)

for cpu in response['Datapoints']:
  print(cpu)

{u'Timestamp': datetime.datetime(2018, 4, 23, 23, 50, tzinfo=tzlocal()), u'Average': 2.2534861111111106, u'Unit': 'Percent'}
{u'Timestamp': datetime.datetime(2018, 4, 22, 23, 50, tzinfo=tzlocal()), u'Average': 2.266131944444444, u'Unit': 'Percent'}
like image 97
helloV Avatar answered Oct 05 '22 14:10

helloV


This will output the average CPU:

    for k, v in response.items():
        if k == 'Datapoints':
        for y in v:
            print(y['Average'])
like image 34
jmoorhead Avatar answered Oct 05 '22 13:10

jmoorhead