Skip to content

Instantly share code, notes, and snippets.

@sudheerchamarthi
Created October 8, 2020 14:40
Show Gist options
  • Save sudheerchamarthi/062f9901f7566d0417111267444121b2 to your computer and use it in GitHub Desktop.
Save sudheerchamarthi/062f9901f7566d0417111267444121b2 to your computer and use it in GitHub Desktop.
import boto3
import datetime
import time
ec2 = boto3.client('ec2', region_name='us-east-1')
instances=ec2.describe_instances()
cloudwatch = boto3.client('cloudwatch')
for instance in range(len(instances['Reservations'])):
instanceID=instances['Reservations'][instance]['Instances'][0]['InstanceId']
instanceType = instances['Reservations'][instance]['Instances'][0]['InstanceType']
for tag in instances['Reservations'][instance]['Instances'][0]['Tags']:
if tag['Key'] == 'Name':
instanceName = tag['Value']
try:
cwResponse = cloudwatch.get_metric_statistics(Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[{'Name': 'InstanceId', 'Value': instanceID}, ], StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=604800), EndTime=datetime.datetime.utcnow(), Period=604800, Statistics=['Average'])
CPUAverage = str(round(cwResponse['Datapoints'][0]['Average']), 2)
except:
CPUAverage = 'NA'
print(instanceID, instanceType, instanceName, CPUAverage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment