Skip to content

Instantly share code, notes, and snippets.

@shevron shevron/LICENSE
Last active Apr 10, 2019

Embed
What would you like to do?
Send EC2 instance memory usage stats to CloudWatch using boto and IAM Roles
#!/usr/bin/env python
'''
Send memory usage metrics to Amazon CloudWatch
This is intended to run on an Amazon EC2 instance and requires an IAM
role allowing to write CloudWatch metrics. Alternatively, you can create
a boto credentials file and rely on it instead.
Original idea based on https://github.com/colinbjohnson/aws-missing-tools
(c) 2015 Shahar Evron, all rights reserved;
You are free to use, modify and redistribute this software in any form
under the conditions described in the LICENSE file included.
'''
import sys
import re
from boto.ec2 import cloudwatch
from boto.utils import get_instance_metadata
def collect_memory_usage():
meminfo = {}
pattern = re.compile('([\w\(\)]+):\s*(\d+)(:?\s*(\w+))?')
with open('/proc/meminfo') as f:
for line in f:
match = pattern.match(line)
if match:
# For now we don't care about units (match.group(3))
meminfo[match.group(1)] = float(match.group(2))
return meminfo
def send_multi_metrics(instance_id, region, metrics, namespace='EC2/Memory',
unit='Percent'):
'''
Send multiple metrics to CloudWatch
metrics is expected to be a map of key -> value pairs of metrics
'''
cw = cloudwatch.connect_to_region(region)
cw.put_metric_data(namespace, metrics.keys(), metrics.values(),
unit=unit,
dimensions={"InstanceId": instance_id})
if __name__ == '__main__':
metadata = get_instance_metadata()
instance_id = metadata['instance-id']
region = metadata['placement']['availability-zone'][0:-1]
mem_usage = collect_memory_usage()
mem_free = mem_usage['MemFree'] + mem_usage['Buffers'] + mem_usage['Cached']
mem_used = mem_usage['MemTotal'] - mem_free
if mem_usage['SwapTotal'] != 0 :
swap_used = mem_usage['SwapTotal'] - mem_usage['SwapFree'] - mem_usage['SwapCached']
swap_percent = swap_used / mem_usage['SwapTotal'] * 100
else:
swap_percent = 0
metrics = {'MemUsage': mem_used / mem_usage['MemTotal'] * 100,
'SwapUsage': swap_percent }
send_multi_metrics(instance_id, region, metrics)
Copyright (c) 2015, Shahar Evron
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
@Atala

This comment has been minimized.

Copy link

commented Jun 22, 2015

Simple & concise, thanks!

@ducu

This comment has been minimized.

Copy link

commented Jan 6, 2016

Anyone made this work with boto3? Thanks!

@hopewise

This comment has been minimized.

Copy link

commented Feb 11, 2016

How to actually use this script? how to install it?

@Arihant-2904

This comment has been minimized.

Copy link

commented Mar 10, 2016

In line number 44 in brackets for metadata, which metadata should be given can anyone let me know.

@longk15t

This comment has been minimized.

Copy link

commented Jul 29, 2016

I got problem: IOError: [Errno 2] No such file or directory: '/proc/meminfo'

What should I do ? I'm sure I have that file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.