CloudWatch Custom Metrics Part Two
Hello Everyone
Welcome to CloudAffaire and this is Debjeet
In the last blog posts, we have discussed how to create our own custom CloudWatch metrics using AWS provided Perl script.
https://cloudaffaire.com/cloudwatch-custom-metrics-part-one/
In this blog post, we are going to create custom matrices for processes inside EC2 instance in CloudWatch using our own shell script and AWS CLI. The shell script will collect the memory utilization of MySQL and Apache process and publish the data in CloudWatch using AWS CLI.
Prerequisite for this demo:
- One running EC2 instance.
- IAM user with proper access in AWS CLI and CloudWatch.
We have already created the IAM user with below policy attached and gathered the IAM users Access Key and Secret Key.
Create CloudWatch custom metrics for EC2 instance:
Step 1: Connect to your EC2 instance and configure AWS CLI using IAM users Access Key and Secret Key.
1 |
aws configure |
Step 2: Check if you are able to access CloudWatch from EC2 instance using AWS CLI
1 2 3 |
aws cloudwatch list-metrics \ --namespace "System/Linux" \ | grep MetricName |
Step 3: Create a shell script to collect and publish data points in CloudWatch.
1 2 3 4 5 6 7 8 9 |
sudo vi sys_proc_mon.sh #!/bin/bash MYSQLMEMORY=$(ps auxf | grep [m]ysqld | awk '{sum=sum+$6}; END {print sum/1024}') APACHEMEMORY=$(ps auxf | grep [h]ttpd | awk '{sum=sum+$6}; END {print sum/1024}') aws cloudwatch put-metric-data --metric-name MysqlMemoryUsed --dimensions InstanceId=i-011aff92cd746a4bb --namespace "System/Linux" --value $MYSQLMEMORY aws cloudwatch put-metric-data --metric-name ApacheMemoryUsed --dimensions InstanceId=i-011aff92cd746a4bb --namespace "System/Linux" --value $APACHEMEMORY sudo chmod +x sys_proc_mon.sh |
Step 4: Execute the shell script and check if data gets published in CloudWatch
1 |
./sys_proc_mon.sh |
Before:
After:
You can also create a CRON job to get continuous memory utilization data for MySQL and Apache.
Hope you have enjoyed this article. Apart from these two methods, you can also use CloudWatch Agent to collect and publish custom metrics. We will cover CloudWatch Agent in the future blog post. In the next blog post, we are going to discuss CloudWatch Dashboard.
To get more details on CloudWatch, please refer below AWS documentation
https://docs.aws.amazon.com/cloudwatch/index.html