Try to get CloudWatch metrics with re: dash python data source

Although it says that re: dash can use python as a data source, there is not much information in the documentation, so I will write a simple execution example.

Overview

Basically, in a dictionary-type variable named "result" http://docs.redash.io/en/latest/dev/results_format.html If you enter the value according to the format specified in, it will be recognized without permission.

Add data source

Go to the Add Data Source screen, set the type to Python, and enter the modules that allow import, separated by commas. I'm entering boto3 and datetime for later use.

Writing a sample query

Set the data source of the query to the data source you added earlier, and enter the following query.

result = {}

add_result_row(result, {'name':'hoge', 'count':5, 'countf':6.3})
add_result_row(result, {'name':'bar', 'count':11, 'countf':3.14159})
add_result_row(result, {'name':'foo', 'count':0, 'countf':99.9999})

add_result_column(result, 'name', '', 'string')
add_result_column(result, 'count', '', 'integer')
add_result_column(result, 'countf', '', 'float')

Since the help methods add_result_row and add_result_column are provided by default, These are used for column definitions and row definitions.

add_result_row adds a row. If you pass the dictionary type that is a pair of column name and value as the second argument, it will be added to result as you like.

add_result_column adds a column definition. Column name in the second argument (name corresponding to the dictionary type to be added to add_result_row) Name for display in the third argument Type as the fourth argument (corresponds to string, integer, float, boolean, date, datetime) To specify.

When executed, the following results will be obtained. スクリーンショット 2015-12-25 17.52.46.png

Writing a query that references external data

In the previous query, the data is solidly written in the source and it is not interesting, so let's write a query to get external data.

This time, let's get the CPU usage of the instance with Amazon CloudWatch.

Preparation

The OS uses the officially distributed ubuntu AMI.

Install boto3 in advance with `` `sudo pip install boto3```. Also, allow access to CloudWatch with IamRole.

Creating a query

Create a new query and write the following code.

'target-instanceId'In the place of, write the ID of the instance you want to get.



 Also, since the graph of re: dash cannot be displayed in units finer than the date, `` `Period = 3600``` is set and the average is taken in hourly units.

 The return value of cloud_watch.get_metric_statistics is looped around, adding CPU usage and date to the row.

 For the detailed return value of cloud_watch.get_metric_statistics, please refer to [Class Method's Blog](http://dev.classmethod.jp/cloud/aws/get_value_of_cloudwatch_using_boto3/).


```python3
import boto3
import datetime

result = {}

cloud_watch = boto3.client('cloudwatch', region_name='ap-northeast-1')

get_metric_statistics = cloud_watch.get_metric_statistics(
                            Namespace='AWS/EC2',
                            MetricName='CPUUtilization',
                            Dimensions=[
                                {
                                    'Name': 'InstanceId',
                                    'Value': 'target-instanceId'
                                }
                            ],
                           StartTime=datetime.datetime.now() - datetime.timedelta(days=1),
                           EndTime=datetime.datetime.now(),
                           Period=3600,
                           Statistics=['Average'])

for d in get_metric_statistics['Datapoints']:
    add_result_row(result, {'average':d['Average'], 'datetime':d['Timestamp']. isoformat()})

add_result_column (result, 'average', 'aaaaa', 'float')
add_result_column (result, 'datetime', '', 'datetime')

If you do this, you will get the following results: スクリーンショット 2015-12-25 18.11.46.png

Also, if you make a line graph, you will get this kind of data. スクリーンショット 2015-12-25 18.12.32.png

You can also use it like a monitoring server by getting the latest data and setting alerts.

Recommended Posts

Try to get CloudWatch metrics with re: dash python data source
I tried to get CloudWatch data with Python
I want to use a python data source in Re: Dash to get query results
[First API] Try to get Qiita articles with Python
Get Youtube data with python
Try to get data while port forwarding to RDS with anaconda.
Get additional data to LDAP with python (Writer and Reader)
[Introduction to Python] How to get data with the listdir function
Get the source of the page to load infinitely with python.
Try to operate Facebook with Python
[Python] Get economic data with DataReader
How to get started with Python
Try to solve the shortest path with Python + NetworkX + social data
Get additional data in LDAP with python
Try to reproduce color film with Python
Try logging in to qiita with Python
[Note] Get data from PostgreSQL with Python
Try working with binary data in Python
Convert Excel data to JSON with python
Convert FX 1-minute data to 5-minute data with Python
Try converting to tidy data with pandas
Try to image the elevation data of the Geographical Survey Institute with Python
Try sending Metrics to datadog via python, DogStatsD
Try to aggregate doujin music data with pandas
Try to solve the man-machine chart with Python
Try to make a "cryptanalysis" cipher with Python
Try to automatically generate Python documents with Sphinx
Try to make a dihedral group with Python
Write CSV data to AWS-S3 with AWS-Lambda + Python
A layman wants to get started with Python
Python script to get note information with REAPER
Try to detect fish with python + OpenCV2.4 (unfinished)
[Introduction to Python] How to get the index of data with a for statement
Try scraping with Python.
Easy analysis sharing with re: dash, an open source data visualization tool Part 2 ~ Graph
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
How to scrape image data from flickr with python
Try to make a command standby tool with python
I tried to get started with blender python script_Part 01
Try to solve the internship assignment problem with Python
Get financial data with python (then a little tinkering)
Try to operate DB with Python and visualize with d3
Reading Note: An Introduction to Data Analysis with Python
I tried to get started with blender python script_Part 02
How to get more than 1000 data with SQLAlchemy + MySQLdb
Try to get the contents of Word with Golang
How to get mouse wheel verdict with Python curses
Get date with python
Try to automate pdf format report creation with Python
I tried to analyze J League data with Python
Data analysis with Python
Get data from database via ODBC with Python (Access)
When I try to update the data on DynamoDB with Python (boto3), I get "ExpressionAttributeNames contains invalid key: Syntax error; key: <key name>"
Easy analysis sharing with re: dash, an open source data visualization tool Part 4 ~ pivot table
Easy analysis sharing with re: dash, an open source data visualization tool Part 3 ~ Google Spreadsheets
[Python] Try to create ring fit data using Amazon Textract [OCR] (Try code review with Code Guru)
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
Easy analysis and sharing with re: dash, an open source data visualization tool Part 1-Installation
Get a list of CloudWatch Metrics and a correspondence table for Unit units with Python boto
Try scraping the data of COVID-19 in Tokyo with Python
I want to be able to analyze data with Python (Part 3)