How to configure Lambda function to get EC2 CPU utilization?

0

Hi, I'm running EC2 instances. I want to get CPU usage by lambda function. But I haven't been able to figure out what should I write with JSON to configure Lambda function. I want to ask if you can show the example codes for lambda function. and I want to get this CPU utilization by everyday and every month. And also possibly Disk usage and memory usage too.

1 Answer
0

The below script helps you to monitor all EC2 instances from Amazon AWS and check CPU utilization. If CPU load more than 50%, it will send email to administrator

import boto3 from datetime import datetime, timedelta from operator import itemgetter import smtplib from email.mime.text import MIMEText

AccessKey = "Your Access Key" SecretKey = "Your Secret Key"

Mail sender function

def SendMail(alert): # Define to/from sender = 'sender email' recipient = 'recipient email'

# Create message
msg = MIMEText(alert)
msg['Subject'] = "CPU Utilization Alert on server with InstanceID %s " % InstanceID
msg['From'] = sender
msg['To'] = recipient

# Create server object with SSL option
server = smtplib.SMTP_SSL('smtp.zoho.com', 465)         # May be another mail server

# Perform operations via server
server.login('mail login', 'mail password')
server.sendmail(sender, [recipient], msg.as_string())
server.quit()

now = datetime.utcnow() # Now time in UTC format past = now - timedelta(minutes=60) # Minus 60 minutes

Amazon Cloud Watch connection

client_cw = boto3.client( 'cloudwatch', aws_access_key_id = AccessKey, aws_secret_access_key = SecretKey,

)

Amazon EC2 connection

client_ec2 = boto3.client( 'ec2', aws_access_key_id = AccessKey, aws_secret_access_key = SecretKey,

)

response = client_ec2.describe_instances() # Get all instances from Amazon EC2

for reservation in response["Reservations"]: for instance in reservation["Instances"]:

    # This will print output the value of the Dictionary key 'InstanceId'
    print(instance["InstanceId"])

    # Get CPU Utilization for each InstanceID
    CPUUtilization = client_cw.get_metric_statistics(
        Namespace='AWS/EC2',
        MetricName='CPUUtilization',
        Dimensions=[{'Name': 'InstanceId', 'Value': instance["InstanceId"]}],
        StartTime=past,
        EndTime=now,
        Period=600,
        Statistics=['Average'])

    datapoints = CPUUtilization['Datapoints']                               # CPU Utilization results
    last_datapoint = sorted(datapoints, key=itemgetter('Timestamp'))[-1]    # Last result
    utilization = last_datapoint['Average']                                 # Last utilization
    load = round((utilization / 100.0), 3)                                  # Last utilization in %
    timestamp = str(last_datapoint['Timestamp'])                            # Last utilization timestamp
    print("{0} load at {1}".format(load, timestamp))

    # Send mail if CPU load more than 50%
    if load > 50:
        InstanceID = instance["InstanceId"]
        SendMail("CPU Utilization more than 50% on server with InstanceID {0}\n"
                 "\n{1}% load at {2} (UTC time)".format(InstanceID, load, timestamp))
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions