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
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.
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.
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'}
This will output the average CPU:
for k, v in response.items():
if k == 'Datapoints':
for y in v:
print(y['Average'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With