Example #1
0
 def cw_alarm(self, cw_conn, instance_id, email_add):
     """ Create cloudwatch alarm on an instance when CPU utilisation is less
     than or equal to 40% for five minutes, and send sns alert to an email address """
     sns = boto.sns.connect_to_region('eu-west-1')
     topic_name = 'cpu_alarm'+instance_id
     new_sns_topic = sns.create_topic(topic_name)
     sns_arn = self.get_sns_arn(new_sns_topic)
     sns.subscribe(sns_arn, 'email', email_add)
     metrics = cw_conn.list_metrics(dimensions={'InstanceId': instance_id}, metric_name="CPUUtilization")
     ec2_alarm = metrics[0].create_alarm(name=topic_name, comparison='<=', threshold=40.0, period=300,
                                         evaluation_periods=2, statistic='Average', alarm_actions=[sns_arn])
     if ec2_alarm:
         print 'cloudwatch alarm created'
Example #2
0
def setAlarm():	
	#An SNS connection object is created by passing the region, key and secret key to the connection_to_region() method
	sns = boto.sns.connect_to_region('eu-west-1',aws_access_key_id=key_id, aws_secret_access_key=secret_key )
	#An cloudwatch connection object is created by passing the region, key and secret key to the connection_to_region() method
	cw = boto.ec2.cloudwatch.connect_to_region("eu-west-1", aws_access_key_id=key_id, aws_secret_access_key=secret_key)
	
	print "\nEnabling Cloudwatch monitoring on running instances..\n"
	
	#Invoke the get_all_topics method to return a dictionary containing all topic arns on the account
	topics = sns.get_all_topics()
	
	#Get the first [0] topic arm from the dictionary
	topic = topics[u'ListTopicsResponse']['ListTopicsResult']['Topics'][0]['TopicArn']
	
	emailAddr = raw_input("Please enter an email address to receive alarm notifications: ")
	
	#emailAddr = "*****@*****.**" 
	
	print "\nSNS email address set to %s\n" % emailAddr	
	#Iterate through the list of reservation objects returned by get_all_reservations()
	#This method returns a list of all EC2 instance objects
	for reservation in conn.get_all_reservations():
		#iterate through all instances in reservation
		for instance in reservation.instances:	
			#Set boolean to alert use if no running instances found
			any_running = False
			
			#for any instances that have their state set to running			
			if instance.state == u'running':
				#Call the monitor_instance method on the EC2 connection object with the specified instance id to enable monitoring
				conn.monitor_instance(instance.id)
				
				alarm_name = 'CPU Utilization < 40 for instance: %s' %instance.id 
				#Set the dimensions for the alarm using the current instance id
				alarm_dimensions = {"InstanceId": instance.id}		
				#Set up the alarm by passing in relevant arguments to the Metric alarm method
				#Notable arguments would be threshold being the % to check against and dimensions being the instances to activate the alarm on
				alarm = MetricAlarm(name = alarm_name, comparison='<', threshold=40, period=300, evaluation_periods=2,namespace='AWS/EC2', metric='CPUUtilization', statistic='Average', alarm_actions=[topic], dimensions = alarm_dimensions)
				#Create the alarm
				cw.create_alarm(alarm)
				print "Alarm set for instance: %s" % instance.id
				#Subscribe to the alarm using the specified email address and the email protocol
				sns.subscribe(topic, "email", emailAddr)
				any_running = True;
			if not any_running:
				print "\nNo running instances found. No alarm set."
Example #3
0
def setAlarm():
    sns = boto.sns.connect_to_region('eu-west-1',
                                     aws_access_key_id=key_id,
                                     aws_secret_access_key=secret_key)
    cw = boto.ec2.cloudwatch.connect_to_region(
        "eu-west-1",
        aws_access_key_id=key_id,
        aws_secret_access_key=secret_key)

    print "\nEnabling Cloudwatch monitoring on running instances..\n"

    topics = sns.get_all_topics()

    topic = topics[u'ListTopicsResponse']['ListTopicsResult']['Topics'][0][
        'TopicArn']

    emailAddr = raw_input(
        "Please enter an email address to receive alarm notifications: ")

    print "\nSNS email address set to %s\n" % emailAddr
    any_running = False
    for reservation in conn.get_all_reservations():
        for instance in reservation.instances:
            if instance.state == u'running':
                any_running = True
                conn.monitor_instance(instance.id)

                alarm_name = 'CPU Utilization < 40 for instance: %s' % instance.id
                alarm_dimensions = {"InstanceId": instance.id}
                alarm = MetricAlarm(name=alarm_name,
                                    comparison='<',
                                    threshold=40,
                                    period=300,
                                    evaluation_periods=2,
                                    namespace='AWS/EC2',
                                    metric='CPUUtilization',
                                    statistic='Average',
                                    alarm_actions=[topic],
                                    dimensions=alarm_dimensions)
                cw.create_alarm(alarm)
                print "Alarm set for instance: %s" % instance.id
                sns.subscribe(topic, "email", emailAddr)
        if not any_running:
            print "\nNo running instances found. No alarm set."
def main():
    parser = optparse.OptionParser('Usage: %prog <options>')
    parser.add_option('-e', '--email', dest='email',
        help='The email address to send notifications to whenever an '
             'alert is triggered.')
    parser.add_option('-n', '--name', dest='name',
        help='The name of the alarm (e.g., BillingAlarm-1000).')
    parser.add_option('-t', '--threshold', dest='threshold',
        help='The dollar amount of estimated monthly charges which, '
             'when exceeded, causes an alert to be triggered.')
    parser.add_option('-p', '--period', dest='period', default=Defaults.PREIOD,
        help='The period in seconds over which the estimated monthly '
             'charges statistic is applied.')
    (opts, args) = parser.parse_args()

    if (0 != len(args) or
        opts.email is None or
        opts.threshold is None):
        parser.print_help()
        return 1

    try:
        sns = boto.connect_sns()

        topic = sns.create_topic('BillingNotifications') \
            ['CreateTopicResponse'] \
            ['CreateTopicResult'] \
            ['TopicArn']

        res = sns.subscribe(topic, 'email', opts.email) \
            ['SubscribeResponse'] \
            ['SubscribeResult'] \
            ['SubscriptionArn']
        if res == 'pending confirmation':
            raw_input('Please confirm subscription. Press [ENTER] when done...')

        cloudwatch = boto.connect_cloudwatch()

        alarm = MetricAlarm(name=opts.name if opts.name is not None
                else 'BillingAlarm-{0}'.format(opts.threshold),
            description='Estimated Monthly Charges',
            alarm_actions=[topic],
            metric=Defaults.METRIC,
            namespace='AWS/Billing',
            statistic=Defaults.STATISTIC,
            dimensions={'Currency':'USD'},
            period=opts.period,
            evaluation_periods=1,
            threshold=int(opts.threshold),
            comparison='>=')
        cloudwatch.create_alarm(alarm)
    except Error, err:
        sys.stderr.write('[ERROR] {0}\n'.format(err))
        return 1
def create_alarm(instance_id):
	global alarmed
	if alarmed == False:
	    sns = boto.sns.connect_to_region('eu-west-1')
	    sns.create_topic('DavidK_Network_Problem') # Create a topic
	    arn = 'arn:aws:sns:eu-west-1:808146113457:DavidK_Network_Problem' #Amazon Resource Name, uniquely identify AWS resources
	    sns.subscribe(arn, "email", "*****@*****.**") # subscribe my email to the topic

	    cloudwatch = boto.ec2.cloudwatch.connect_to_region('eu-west-1')
	    # create a list holding the metric that the alarm will be based on
	    metrics = cloudwatch.list_metrics(dimensions={'InstanceId' : instance_id},metric_name='NetworkIn')
	    # call to create the autoscaling group and to get policy arn for the alarm
	    as_policy_arn = create_auto_scaling(instance_id)
	    # create the alarm
	    alarm = metrics[0].create_alarm(name='Network_Usage_Alarm', comparison='>=', threshold=500000, period=60,
                    evaluation_periods=1, statistic='Average', alarm_actions=[arn,as_policy_arn])
	    if alarm:
	    	print '\n----------'
		    print 'Alarm set'
		    print '----------\n'
		    alarmed = True
	    else:
		    print '\nAlarm has not been set\n'
credentials = {'aws_access_key_id': args.aws_access_key_id, 'aws_secret_access_key': args.aws_secret_access_key}

def isSelected(region):
    return True if region.name.find(args.region) != -1 else False

def createTopicArn(region_name, topic_name):
    from boto_cli.iam.accountinfo import AccountInfo
    iam = boto.connect_iam(**credentials)
    accountInfo = AccountInfo(iam)
    account = accountInfo.describe()
    return 'arn:aws:sns:' + region_name + ':' + account.id + ':' + topic_name

# execute business logic
heading = "Subscribing to SNS topics named '" + args.topic + "'"
regions = boto.sns.regions()
if args.region:
    heading += " (filtered by region '" + args.region + "')"
    regions = filter(isSelected, regions)

print heading + ":"
for region in regions:
    pprint(region.name, indent=2)
    try:
        sns = boto.connect_sns(region=region, **credentials)
        arn = createTopicArn(region.name, args.topic)
        print 'Subscribing to topic ' + arn + ' with protocol ' + args.protocol + ' and endpoint ' + args.endpoint
        sns.subscribe(arn, args.protocol, args.endpoint)
    except boto.exception.BotoServerError, e:
        print e.error_message
Example #7
0
def checkLogs(buckets):
	
	#Set ignored id list, add your own account ID here
	ignoredId = []
	
	#Static email address for testing
	#emailAddr = "*****@*****.**" 

	#Set the name of our cloudTrails bucket
	ct_name = "cloudtrailadam"
	
	for bucket in buckets:			
		#Iterate through buckets and find the cloudtrail bucket
		if bucket.name == ct_name:
			#Iterate though all keys in the bucket such that key points to the last one
			#which is the last created log file
			for key in bucket:
				#Check if key is a file and not a folder by checking the end of the path
				if not key.name.endswith('/'):
					#Construct an empty StringIO object
					f = StringIO.StringIO()
					#Using the boto s3 method get_file, retrieve the file from the S3 key and place the data in the StringIO buffer
					key.get_file(f)
					#Set the position of the read/write pointer to the beginning of the file
					f.seek(0, 0)
					#Construct a new GzipFile object and pass it the file object contained in f
					gzfile = gzip.GzipFile(fileobj=f)
					#get the data from the file using pythons .read method
					data = gzfile.read()
					#Pass the data to the .loads method in the json library which returns an object 
					j = json.loads(data)
					#Set the parent key from the JSON to look for keys within the main key
					parent = j["Records"]	
					#Iterate though the json parent key again
					for item in parent:
						#If the accountId of any event does not match user specified one.
						if item['userIdentity']['accountId'] not in ignoredId: 
							print "\nAccess from unknown account: ", item['userIdentity']['accountId'],  " found!\n"
							#print the details of the event
							print "Event Details: ", item["sourceIPAddress"], item["userIdentity"]["type"], item["userIdentity"]["accountId"], item["eventName"], item["eventTime"]
							
							while(True):
								input = raw_input("\nDo you wish to ignore events from this account ID? (Y/N) ").lower()							
								if input in ('yes', 'y', 'ye'):
									#Add the event account ID to the list of ignored IDs
									ignoredId.append(item['userIdentity']['accountId'])
									break
								elif input in ('no', 'n', '0'):								
									input = raw_input("Do you wish to be notified of the first event of this ID via email? (Y/N) > ").lower()
									if input in ('yes', 'y', 'ye'):					
										#Set up email address
										emailAddr = raw_input("Please enter an email address to receive alarm notifications: ")
										#Create SNS connection
										sns = boto.sns.connect_to_region("eu-west-1", aws_access_key_id=key_id, aws_secret_access_key=secret_key)
										#Pull all of the topic ARNs on the account and store them in topics
										topics = sns.get_all_topics()
										#Get the first topic ARN and store it in topic
										topic = topics[u'ListTopicsResponse']['ListTopicsResult']['Topics'][0]['TopicArn']
										#Set up email message body to contain event information
										msg = "Event details -  Source IP: " + str(item["sourceIPAddress"]) + " :  Account ID: " + str(item["userIdentity"]["accountId"]) + " :  Event type: " + str(item["eventName"]) + " :  Event time: " +  str(item["eventTime"])
										#Set up email message subject
										subject = "Unauthorised account access"
										#Public this message to SNS
										sns.publish(topic, msg, subject)
										#Subscribe to the alarm using the specified email address and the email protocol
										sns.subscribe(topic, "email", emailAddr)
										#Add ID to ignored list to continue checking for other unauthorised accounts
										ignoredId.append(item['userIdentity']['accountId'])
										break
									elif input in ('no', 'n', '0'):
										break
									else:
										print "Invalid command"
								else:
									print "Invalid command"
					
	print "\n\nCheck complete\n"
Example #8
0
# configure command line argument parsing
parser = argparse.ArgumentParser(description='Subscribe to a SNS topic in all/some available SNS regions',
                                 parents=[bc.build_region_parser(), bc.build_common_parser()])
parser.add_argument("topic", help="A topic name")
parser.add_argument("protocol", help="The protocol used to communicate with the subscriber. Current choices are: email|email-json|http|https|sqs")
parser.add_argument("endpoint", help="The endpoint to receive notifications.")
args = parser.parse_args()

# process common command line arguments
log = logging.getLogger('botocross')
bc.configure_logging(log, args.log_level)
credentials = bc.parse_credentials(args)
regions = bc.filter_regions(boto.sns.regions(), args.region)

# execute business logic
log.info("Subscribing to SNS topics named '" + args.topic + ' with protocol ' + args.protocol + ' and endpoint ' + args.endpoint + "':")

iam = boto.connect_iam(**credentials)
for region in regions:
    pprint(region.name, indent=2)
    try:
        sns = boto.connect_sns(region=region, **credentials)
        arn = bc.create_arn(iam, 'sns', region.name, args.topic)
        log.debug('Subscribing to topic ' + arn + ' with protocol ' + args.protocol + ' and endpoint ' + args.endpoint)
        result = sns.subscribe(arn, args.protocol, args.endpoint)
        print result['SubscribeResponse']['SubscribeResult']['SubscriptionArn']

    except boto.exception.BotoServerError, e:
        log.error(e.error_message)
Example #9
0
def checkLogs(buckets):

    #Set ignored id list, add your own account ID here
    ignoredId = []

    #Static email address for testing
    #emailAddr = "*****@*****.**"

    #Set the name of our cloudTrails bucket
    ct_name = "cloudtrailadam"

    for bucket in buckets:
        #Iterate through buckets and find the cloudtrail bucket
        if bucket.name == ct_name:
            #Iterate though all keys in the bucket such that key points to the last one
            #which is the last created log file
            for key in bucket:
                #Check if key is a file and not a folder by checking the end of the path
                if not key.name.endswith('/'):
                    #Construct an empty StringIO object
                    f = StringIO.StringIO()
                    #Using the boto s3 method get_file, retrieve the file from the S3 key and place the data in the StringIO buffer
                    key.get_file(f)
                    #Set the position of the read/write pointer to the beginning of the file
                    f.seek(0, 0)
                    #Construct a new GzipFile object and pass it the file object contained in f
                    gzfile = gzip.GzipFile(fileobj=f)
                    #get the data from the file using pythons .read method
                    data = gzfile.read()
                    #Pass the data to the .loads method in the json library which returns an object
                    j = json.loads(data)
                    #Set the parent key from the JSON to look for keys within the main key
                    parent = j["Records"]
                    #Iterate though the json parent key again
                    for item in parent:
                        #If the accountId of any event does not match user specified one.
                        if item['userIdentity']['accountId'] not in ignoredId:
                            print "\nAccess from unknown account: ", item[
                                'userIdentity']['accountId'], " found!\n"
                            #print the details of the event
                            print "Event Details: ", item[
                                "sourceIPAddress"], item["userIdentity"][
                                    "type"], item["userIdentity"][
                                        "accountId"], item["eventName"], item[
                                            "eventTime"]

                            while (True):
                                input = raw_input(
                                    "\nDo you wish to ignore events from this account ID? (Y/N) "
                                ).lower()
                                if input in ('yes', 'y', 'ye'):
                                    #Add the event account ID to the list of ignored IDs
                                    ignoredId.append(
                                        item['userIdentity']['accountId'])
                                    break
                                elif input in ('no', 'n', '0'):
                                    input = raw_input(
                                        "Do you wish to be notified of the first event of this ID via email? (Y/N) > "
                                    ).lower()
                                    if input in ('yes', 'y', 'ye'):
                                        #Set up email address
                                        emailAddr = raw_input(
                                            "Please enter an email address to receive alarm notifications: "
                                        )
                                        #Create SNS connection
                                        sns = boto.sns.connect_to_region(
                                            "eu-west-1",
                                            aws_access_key_id=key_id,
                                            aws_secret_access_key=secret_key)
                                        #Pull all of the topic ARNs on the account and store them in topics
                                        topics = sns.get_all_topics()
                                        #Get the first topic ARN and store it in topic
                                        topic = topics[u'ListTopicsResponse'][
                                            'ListTopicsResult']['Topics'][0][
                                                'TopicArn']
                                        #Set up email message body to contain event information
                                        msg = "Event details -  Source IP: " + str(
                                            item["sourceIPAddress"]
                                        ) + " :  Account ID: " + str(
                                            item["userIdentity"]["accountId"]
                                        ) + " :  Event type: " + str(
                                            item["eventName"]
                                        ) + " :  Event time: " + str(
                                            item["eventTime"])
                                        #Set up email message subject
                                        subject = "Unauthorised account access"
                                        #Public this message to SNS
                                        sns.publish(topic, msg, subject)
                                        #Subscribe to the alarm using the specified email address and the email protocol
                                        sns.subscribe(topic, "email",
                                                      emailAddr)
                                        #Add ID to ignored list to continue checking for other unauthorised accounts
                                        ignoredId.append(
                                            item['userIdentity']['accountId'])
                                        break
                                    elif input in ('no', 'n', '0'):
                                        break
                                    else:
                                        print "Invalid command"
                                else:
                                    print "Invalid command"

    print "\n\nCheck complete\n"
Example #10
0
def setAlarm():
    #An SNS connection object is created by passing the region, key and secret key to the connection_to_region() method
    sns = boto.sns.connect_to_region('eu-west-1',
                                     aws_access_key_id=key_id,
                                     aws_secret_access_key=secret_key)
    #An cloudwatch connection object is created by passing the region, key and secret key to the connection_to_region() method
    cw = boto.ec2.cloudwatch.connect_to_region(
        "eu-west-1",
        aws_access_key_id=key_id,
        aws_secret_access_key=secret_key)

    print "\nEnabling Cloudwatch monitoring on running instances..\n"

    #Invoke the get_all_topics method to return a dictionary containing all topic arns on the account
    topics = sns.get_all_topics()

    #Get the first [0] topic arm from the dictionary
    topic = topics[u'ListTopicsResponse']['ListTopicsResult']['Topics'][0][
        'TopicArn']

    emailAddr = raw_input(
        "Please enter an email address to receive alarm notifications: ")

    #emailAddr = "*****@*****.**"

    print "\nSNS email address set to %s\n" % emailAddr
    #Iterate through the list of reservation objects returned by get_all_reservations()
    #This method returns a list of all EC2 instance objects
    for reservation in conn.get_all_reservations():
        #iterate through all instances in reservation
        for instance in reservation.instances:
            #Set boolean to alert use if no running instances found
            any_running = False

            #for any instances that have their state set to running
            if instance.state == u'running':
                #Call the monitor_instance method on the EC2 connection object with the specified instance id to enable monitoring
                conn.monitor_instance(instance.id)

                alarm_name = 'CPU Utilization < 40 for instance: %s' % instance.id
                #Set the dimensions for the alarm using the current instance id
                alarm_dimensions = {"InstanceId": instance.id}
                #Set up the alarm by passing in relevant arguments to the Metric alarm method
                #Notable arguments would be threshold being the % to check against and dimensions being the instances to activate the alarm on
                alarm = MetricAlarm(name=alarm_name,
                                    comparison='<',
                                    threshold=40,
                                    period=300,
                                    evaluation_periods=2,
                                    namespace='AWS/EC2',
                                    metric='CPUUtilization',
                                    statistic='Average',
                                    alarm_actions=[topic],
                                    dimensions=alarm_dimensions)
                #Create the alarm
                cw.create_alarm(alarm)
                print "Alarm set for instance: %s" % instance.id
                #Subscribe to the alarm using the specified email address and the email protocol
                sns.subscribe(topic, "email", emailAddr)
                any_running = True
            if not any_running:
                print "\nNo running instances found. No alarm set."
Example #11
0
def checkLogs(buckets):

    ignoredId = []

    ct_name = "cloudtrailadam"

    for bucket in buckets:
        if bucket.name == ct_name:
            for key in bucket:
                if not key.name.endswith('/'):
                    f = StringIO.StringIO()
                    key.get_file(f)
                    f.seek(0, 0)
                    gzfile = gzip.GzipFile(fileobj=f)
                    data = gzfile.read()
                    j = json.loads(data)
                    parent = j["Records"]
                    for item in parent:
                        if item['userIdentity']['accountId'] not in ignoredId:
                            print "\nAccess from unknown account: ", item[
                                'userIdentity']['accountId'], " found!\n"
                            print "Event Details: ", item[
                                "sourceIPAddress"], item["userIdentity"][
                                    "type"], item["userIdentity"][
                                        "accountId"], item["eventName"], item[
                                            "eventTime"]

                            while (True):
                                input = raw_input(
                                    "\nDo you wish to ignore events from this account ID? (Y/N) "
                                ).lower()
                                if input in ('yes', 'y', 'ye'):
                                    ignoredId.append(
                                        item['userIdentity']['accountId'])
                                    break
                                elif input in ('no', 'n', '0'):
                                    input = raw_input(
                                        "Do you wish to be notified of the first event of this ID via email? (Y/N) > "
                                    ).lower()
                                    if input in ('yes', 'y', 'ye'):
                                        emailAddr = raw_input(
                                            "Please enter an email address to receive alarm notifications: "
                                        )
                                        sns = boto.sns.connect_to_region(
                                            "eu-west-1",
                                            aws_access_key_id=key_id,
                                            aws_secret_access_key=secret_key)
                                        topics = sns.get_all_topics()
                                        topic = topics[u'ListTopicsResponse'][
                                            'ListTopicsResult']['Topics'][0][
                                                'TopicArn']
                                        msg = "Event details -  Source IP: " + str(
                                            item["sourceIPAddress"]
                                        ) + " :  Account ID: " + str(
                                            item["userIdentity"]["accountId"]
                                        ) + " :  Event type: " + str(
                                            item["eventName"]
                                        ) + " :  Event time: " + str(
                                            item["eventTime"])
                                        subject = "Unauthorised account access"
                                        sns.publish(topic, msg, subject)
                                        sns.subscribe(topic, "email",
                                                      emailAddr)
                                        ignoredId.append(
                                            item['userIdentity']['accountId'])
                                        break
                                    elif input in ('no', 'n', '0'):
                                        break
                                    else:
                                        print "Invalid command"
                                else:
                                    print "Invalid command"

    print "\n\nCheck complete\n"
Example #12
0
def alarmProcessor():
    
	# Firstly we need to connect to the Simple Notification Service and CloudWatch service - this was a bit tricky and again the documentation was unclear.  I thought you would use boto.connect_sns(region=reg) 
	# which seems to successfully connect and is similar to how we connected to S3 and EC2 services.  However calling methods e.g. get_all_topics() yields the error "The requested version (2010-03-31) of 
	# service AmazonEC2 does not exist".  On further investigation I found that to connect use boto.sns.connect_to_region().  You have to supply the region as an argument - note that it expected a string 
	# not a region object - which again is inconsistent with EC2. To connect to the CloudWatch service as with SNS you have to use the connect_to_region() method
    sns = boto.sns.connect_to_region("eu-west-1")
    cw = boto.ec2.cloudwatch.connect_to_region("eu-west-1")
    
    if (not args.clear):
        print "\nCreating new topics (+ subscription) and alarms:\n"
        # Once connected we create a topic which is basically an access point composed of an identifier and recipients to send message to. create_topic() returns a unique ARN (Amazon Resource Name) which
        # will include the service name (SNS), region, AWS ID of the user and the topic name - this is a dict so we need to go three levels in to get the actual ARN number.  We will use the arn when
        # we create a subscription which is how we link a topic to an endpoint like an email address.

        topicName = 'TopicStephenCIT-1-UID'+str(random.randrange(1000000))
        response = sns.create_topic(topicName)
        topicARN = response['CreateTopicResponse']['CreateTopicResult']['TopicArn']
        
        print '\tTopic ARN created: ',topicARN
		
		#Subscribe links a topic with an endpoint - in this case an email address
        sns.subscribe(topicARN, 'email',  args.email)

        #We now have topic/subscription - the email address supplied will have to accept the AWS Notification Subscription Confirmation‏ email message to ensure they get alerts
        # We will now create a unique alarm per instance.  We can use the create_alarm method which expects a  boto.ec2.cloudwatch.alarm.MetricAlarm object.  This object defines 
		# all the properties of the alarm - name,metric,topic etc. We loop through all the instance and create an alarm for each instance.  Note we use the ARN that was created 
		# above which ties the alarm to notification logic
                                                   
        for index, inst in enumerate(instances):
            alarmName = "StephenMurrayCPU-" + str(index) + inst.id +'-UID' + str(random.randrange(1000000))
            alarm = boto.ec2.cloudwatch.MetricAlarm(name=alarmName, namespace='AWS/EC2',metric='CPUUtilization',
                                                    statistic='Average',comparison='<', threshold='40',period='60', evaluation_periods=2,
                                                    dimensions = {"InstanceId": inst.id},
                                                    alarm_actions= topicARN)
            cw.create_alarm(alarm)
            print "\tAlarm created", alarmName
    
    else:
        print "\nClearing topics, subscriptions (confirmed) and alarms:\n"
        
        #Get all topics
        returnAllTopicsObject = sns.get_all_topics()
        #to access the ARN field we need have to go 3 levels deep into returned object
        topics = returnAllTopicsObject['ListTopicsResponse']['ListTopicsResult']['Topics']

        #now we have a list containing dicts where the only value is the TopicArn which is what we need to supply the delete method
        # only do action if list is not empty - there has to be some topics to delete
        if topics:
            for t in (topics):
                topicARNDelete = t['TopicArn']
                #delete topics
                sns.delete_topic(topicARNDelete)
                print "\tTopic Deleted: ", topicARNDelete
        else:
            print "\tNo topics found"

        # Get all subscriptions
        # Very similar to topics - get subscriptions, extract relevant parameter from retuned dict object, loop through, get SubscriptionArn
        # and send for deletion - also do a check to ensure subscriptions exist

        returnAllSubObject = sns.get_all_subscriptions()
        #to access the Sub ARN field we need have to go 3 levels deep into returned object
        subscriptions = returnAllSubObject['ListSubscriptionsResponse']['ListSubscriptionsResult']['Subscriptions']

        if subscriptions:
            for s in (subscriptions):
                subARNDelete = s['SubscriptionArn']
                #delete subscription only if returned value is not equal to PendingConfirmation
                if (subARNDelete != 'PendingConfirmation'):
                    sns.unsubscribe(subARNDelete)
                    print "\tSunscription Deleted: ", subARNDelete
        else:
            print "\tNo subscriptions found"

        #Get all alarms
        #describe_alarms() returns a list of boto.ec2.cloudwatch.alarm.MetricAlarms object from which we can extract the alarm name (.name method) which we can
        # use to delete it - Note in this case we do not require the ARN to delete - on testing with IDLE it was noted that when a complete arn
        # arn:aws:cloudwatch:eu-west-1:135577527805:alarm:StephenMurrayCPU0i-690b332b was supplied the delete_alarms() method returned True even though it was
        # not deleted...this is not good as as when StephenMurrayCPU0i-690b332b was supplied it deleted the alarm and also returned True.

        alarms = cw.describe_alarms()
        if alarms:
            for a in (alarms):
                cw.delete_alarms(a.name)
                print "\tAlarms Deleted: ", a.name
        else:
            print "\tNo alarms found"
Example #13
0
def main():
    parser = optparse.OptionParser('Usage: %prog <options>')
    parser.add_option(
        '-e',
        '--email',
        dest='email',
        help='The email address to send notifications to whenever an '
        'alert is triggered.')
    parser.add_option('-n',
                      '--name',
                      dest='name',
                      help='The name of the alarm (e.g., BillingAlarm-1000).')
    parser.add_option(
        '-t',
        '--threshold',
        dest='threshold',
        help='The dollar amount of estimated monthly charges which, '
        'when exceeded, causes an alert to be triggered.')
    parser.add_option(
        '-p',
        '--period',
        dest='period',
        default=Defaults.PREIOD,
        help='The period in seconds over which the estimated monthly '
        'charges statistic is applied.')
    (opts, args) = parser.parse_args()

    if (0 != len(args) or opts.email is None or opts.threshold is None):
        parser.print_help()
        return 1

    try:
        sns = boto.connect_sns()

        topic = sns.create_topic('BillingNotifications') \
            ['CreateTopicResponse'] \
            ['CreateTopicResult'] \
            ['TopicArn']

        res = sns.subscribe(topic, 'email', opts.email) \
            ['SubscribeResponse'] \
            ['SubscribeResult'] \
            ['SubscriptionArn']
        if res == 'pending confirmation':
            raw_input(
                'Please confirm subscription. Press [ENTER] when done...')

        cloudwatch = boto.connect_cloudwatch()

        alarm = MetricAlarm(name=opts.name if opts.name is not None else
                            'BillingAlarm-{0}'.format(opts.threshold),
                            description='Estimated Monthly Charges',
                            alarm_actions=[topic],
                            metric=Defaults.METRIC,
                            namespace='AWS/Billing',
                            statistic=Defaults.STATISTIC,
                            dimensions={'Currency': 'USD'},
                            period=opts.period,
                            evaluation_periods=1,
                            threshold=int(opts.threshold),
                            comparison='>=')
        cloudwatch.create_alarm(alarm)
    except Error, err:
        sys.stderr.write('[ERROR] {0}\n'.format(err))
        return 1