Approach1. Using awscli (you don't have to make codes)
1. before collecting some metrics from your instance, your instance must be lauched with CloudWatchFullAccess IAM role.
ref: http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/UsingIAM.html
Amazon CloudWatch integrates with AWS Identity and Access Management (IAM) so that you can specify which CloudWatch actions a user in your AWS Account can perform. For example, you could create an IAM policy that gives only certain users in your organization permission to use GetMetricStatistics . They could then use the action to retrieve data about your cloud resources. |
* in my case, I made new role(named cloudwatch_test) on IAM service with CloudWatchFullAccess, CloudWatchLogsFullAccess policies. and launch ec2 instance with this IAM role.
2. follow this. to install cloudwatch tool stuffs
http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/mon-scripts-perl.html
3. After installing perl stuffs and finishing role settings, you can use perl command like this.
$ sudo mv aws-scripts-mon /usr/local/bin/aws-scripts-mon
$ echo "* * * * * ubuntu /usr/local/bin/aws-scripts-mon/mon-put-instance-data.pl --mem-used --mem-avail --disk-path=/dev/xvda1 --disk-space-used --dis-space-avail --from-cron" | sudo tee /etc/cron.d/aws-monitor-mem-disk-usage
* "ubuntu" is user name
now you can check your custom metric in Ec2 monitoring->View all CloudWatch metrics->Metrics-> Linux System Metrics
* if you want to monitor your existing ec2 instance, unfortunately there is no way. I tried below, but it was not working.
(you should install awscli tool first, just type $sudo apt-get install awscli, $aws configure)
1. aws iam create-instance-profile --instance-profile-name CloudWatchProfile
2. aws iam add-role-to-instance-profile --instance-profile-name CloudWatchProfile --role-name cloudwatch_test
Approach2. Using Boto (you have to do some works, but could be more flexible)
http://arr.gr/blog/2013/08/monitoring-ec2-instance-memory-usage-with-cloudwatch/
followed record.
1. make t2 micro ec2 instance (ubuntu)
2. install prerequisites
$sudo apt-get update
$sudo apt-get install python-pip
$sudo pip install boto
3. setup boto config file
$sudo vim /etc/boto.cfg
[Credentials]
aws_access_key_id = <your_access_key_here>
aws_secret_access_key = <your_secret_key_here>
4. get source code and set to cron job
$ curl https://gist.githubusercontent.com/shevron/6204349/raw/cw-monitor-memusage.py | sudo tee /usr/local/bin/cw-monitor-memusage.py
$ sudo chmod +x /usr/local/bin/cw-monitor-memusage.py
$ echo "***** ubuntu /usr/local/bin/cw-monitor-memusage.py" | sudo tee /etc/cron.d/cw-monitor-memusage
* "ubuntu" is user name
5. check it in AWS management console
Ec2 monitoring->View all CloudWatch metrics->Metrics-> Custom Metrics (it will take a time, wait until this menu created)