diff --git a/n2cw/aws.py b/n2cw/aws.py index 7c83200..10a9c00 100644 --- a/n2cw/aws.py +++ b/n2cw/aws.py @@ -1,8 +1,8 @@ import botocore.session import urllib2 - AWS_MD_AZ_URL = 'http://169.254.169.254/latest/meta-data/placement/availability-zone' +AWS_INSTANZE_ID_URL = 'http://169.254.169.254/latest/meta-data/instance-id' def detect_region(): @@ -11,6 +11,12 @@ def detect_region(): except urllib2.URLError: return None +def detect_instance_id(): + try: + return urllib2.urlopen(AWS_INSTANZE_ID_URL, timeout=1).read()[:-1] + except urllib2.URLError: + return None + def cloudwatch_client(profile=None, region=None): if region is None: @@ -21,7 +27,6 @@ def cloudwatch_client(profile=None, region=None): session.set_config_variable('profile', profile) return session.create_client('cloudwatch') - class TestClient(object): def __init__(self): import logging @@ -33,13 +38,17 @@ def put_metric_data(self, **kwargs): class CW(object): - def __init__(self, namespace, base_name, dimensions=None, test=False): + def __init__(self, namespace, base_name, instance_id = False, dimensions=None, test=False): self.namespace = namespace self.base_name = base_name self.dimensions = [] + self.data = [] + for k, v in dimensions.iteritems(): self.dimensions.append({'Name': k, 'Value': v}) - self.data = [] + + if instance_id: + self.dimensions.append({'Name': 'instance-id', 'Value': detect_instance_id()}) if test: self.client = TestClient() diff --git a/n2cw/cli.py b/n2cw/cli.py index bcaf083..328b1e3 100644 --- a/n2cw/cli.py +++ b/n2cw/cli.py @@ -31,6 +31,8 @@ def cli(args=sys.argv[:]): ap = ArgumentParser(usage=usage, description=__doc__) ap.add_argument('--dimensions', metavar='key=value,key=value', default={}, action=ParseKv, help='CloudWatch metric dimensions') + ap.add_argument('--instance_id', action='store_true', + help='Add instance-id as a dimension\nWARNING: Will overwrite instance-id given via --dimensions option') ap.add_argument('--noop', action='store_true', help='Don\'t push metrics, just log') ap.add_argument('namespace', help='CloudWatch namespace') @@ -54,7 +56,7 @@ def cli(args=sys.argv[:]): result = e.returncode output = e.output - cw = aws.CW(args.namespace, args.base_name, args.dimensions, args.noop) + cw = aws.CW(args.namespace, args.base_name, args.instance_id, args.dimensions, args.noop) if args.send_status: cw.add('Status', result) if args.send_perfdata: