I tried to get CloudWatch data with Python

Trigger

Every day I check the status of the server on the CloudWatch dashboard. When you come to work, first check the dashboard in order ... It's annoying! : persevere: I want to get dashboard information at once! Alright, let's write in Python!

Get CloudWatch information with Python

It would be nice to use Boto3's get_metric_statistics (). As per Official Documentation, first prepare to load CloudWatch with Boto3.


import boto3
client = boto3.client('cloudwatch')

It seems that get_metric_statistics () is used as follows.

response = client.get_metric_statistics(
           Namespace = 'string',
           MetricName = 'string',
           Dimensions = [
             {
               'Name': 'string',
               'Value': 'string'
             },
           ],
           StartTime = datetime(2020, 2, 11),
           EndTime = datetime(2020, 2, 11),
           Period = 123,
           Statistics = [
             'SampleCount'|'Average'|'Sum'|'Minimum'|'Maximum',
           ])

Namespace ʻAWS / EC2 or ʻAWS / ElastiCache or ʻAWS / RDS. It's written at the top of the information that appears when you hover your mouse cursor over the detailed information on the CloudWatch Graphed Metrics` tab. CloudWatch.png

MetricName CPUUtilization, MemoryUtilization, DiskSpaceAvailable, etc. It's written above the separator line, the second from the top of the information that appears when you hover your mouse cursor over the details on the CloudWatch Graphed Metrics tab.

Dimensions ʻInstanceId, CacheClusterId, DBInstanceIdentifier, etc. It's written below the information separator that appears when you hover your mouse cursor over the detailed information on the CloudWatch Graphed Metricstab. (All dimensions information below the dividing line) As in the example above, Dimensions is written in the following form.Dimensions=[{'Name': 'string', 'Value': 'string'}] So specifically Dimensions = [{'Name':'InstanceId','Value':'i-xxxxxxxxxxx'}] Dimensions=[{'Name': 'Role', 'Value': 'WRITER'}, {'Name': 'DBClusterIdentifier', 'Value': 'xxxxxxxxxxx'}]` It will be shaped like.

Period Write the period in seconds. So 1 minute → 60 5 minutes → 300 24 hours → 86400

Statistics Write statistics.

response

The response of get_metric_statistics () is as follows.

{'Label': 'CPUUtilization', 'Datapoints': [{'Timestamp': datetime.datetime(2020, 2, 10, 19, 8, tzinfo=tzutc()), 'Maximum': 6.66666666666667, 'Unit': 'Percent'}], 'ResponseMetadata': {'RequestId': 'xxxxxxxxxxx', 'HTTPStatusCode': 200, ...(abridgement)

So The value is response ['Datapoints'] [0] [value specified in Statistics (Maximum in the above response)] The unit of the value is response ['Datapoints'] [0] ['Unit'] It seems that you can make it feel good if you use around.

What I actually wrote (part)

Since I was visually checking with CloudWatch every day, in this script I will get the past 24 hours from the script execution date and time. Once you have a script, you may want to run it regularly with cron.

import boto3
from datetime import datetime, timedelta

client = boto3.client('cloudwatch')

def get_metric_statistics(name_space, metric_name, dimensions_values, statistic):
    #Get CloudWatch Information
    response = client.get_metric_statistics(
               #For CPU usage`AWS/EC2`Enter
               Namespace = name_space,
               #For CPU usage`CPUUtilization`Enter
               MetricName = metric_name,
               # `[{'Name': 'InstanceId', 'Value': instance_id}]`Enter
               Dimensions = dimensions_values,
               #Start date and time`Script execution date and time-1 day`Specified by
               StartTime = datetime.now() + timedelta(days = -1),
               #End date and time`Script execution date and time`Specified by
               EndTime = datetime.now(),
               #Specify 24 hours
               Period = 86400,
               # `Maximum`Enter
               Statistics = [statistic]
               )

    #Output statement creation
    response_text = name_space + ' ' + metric_name + statistic + ': ' + str(response['Datapoints'][0][statistic]) + ' ' + response['Datapoints'][0]['Unit']
    print(response_text)

#Output target metric
instance_id = 'i-xxxxxxxxxxx'
#CPU usage
get_metric_statistics('AWS/EC2', 'CPUUtilization', [{'Name': 'InstanceId', 'Value': instance_id}], 'Maximum')
#Memory usage
get_metric_statistics('System/Linux', 'MemoryUtilization', [{'Name': 'InstanceId', 'Value': instance_id}], 'Maximum')

Output result

AWS/EC2 CPUUtilizationMaximum: 6.66666666666667 Percent
System/Linux MemoryUtilizationMaximum: 18.1909615159559 Percent

Summary

I tried to get CloudWatch information from a Python script. This time, I used a pattern with only one Datapoints, but depending on the specified period, there will be multiple outputs. In that case, please aim at the necessary data with a good feeling by loop processing.

We're hiring! We are developing an AI chatbot. If you are interested, please feel free to contact us from the Wantedly page!

Reference article

Boto3 Docs CloudWatch

Recommended Posts

I tried to get CloudWatch data with Python
I tried to get started with blender python script_Part 01
I tried to get started with blender python script_Part 02
I tried to analyze J League data with Python
I tried to make various "dummy data" with Python faker
I tried to get started with Hy
[Python] A memo that I tried to get started with asyncio
[Pandas] I tried to analyze sales data with Python [For beginners]
Try to get CloudWatch metrics with re: dash python data source
[Python] I tried to get various information using YouTube Data API!
I tried to save the data with discord
I tried to output LLVM IR with Python
I tried to automate sushi making with python
I tried fp-growth with python
I tried scraping with Python
Get Youtube data with python
I tried gRPC with Python
I tried scraping with python
[Data science basics] I tried saving from csv to mysql with python
I tried to get the authentication code of Qiita API with Python.
I tried fMRI data analysis with python (Introduction to brain information decoding)
I tried to get the movie information of TMDb API with Python
I tried to implement Minesweeper on terminal with python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
I tried to implement an artificial perceptron with python
I tried to automatically generate a password with Python3
I tried to solve the problem with Python Vol.1
[Python] I tried to get Json of squid ring 2
I tried to solve AOJ's number theory with Python
Link to get started with python
I tried to touch Python (installation)
I tried web scraping with python.
[Python] Get economic data with DataReader
How to get started with Python
I want to debug with Python
I tried running prolog with python 3.8.2.
I tried SMTP communication with Python
I tried to get and analyze the statistical data of the new corona with Python: Data of Johns Hopkins University
I tried to find the entropy of the image with python
I want to be able to analyze data with Python (Part 3)
I tried to simulate how the infection spreads with Python
I tried various methods to send Japanese mail with Python
I want to be able to analyze data with Python (Part 1)
I want to be able to analyze data with Python (Part 4)
I want to be able to analyze data with Python (Part 2)
I tried "How to get a method decorated in Python"
I tried to get started with Hy ・ Define a class
[Python] I tried to visualize tweets about Corona with WordCloud
Mayungo's Python Learning Episode 3: I tried to print numbers with print
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to divide the file into folders with Python
Get additional data to LDAP with python (Writer and Reader)
[Introduction to Python] How to get data with the listdir function
I tried to get data from AS / 400 quickly using pypyodbc
I tried to aggregate & compare unit price data by language with Real Gachi by Python
I tried scraping food recall information with Python to create a pandas data frame
I tried to summarize Python exception handling
I tried to implement PLSA in Python
[Note] Get data from PostgreSQL with Python
I tried to implement Autoencoder with TensorFlow