如何在创建sns主题时将发布消息附加到sns主题

2024-03-29 09:10:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用boto3和python创建一个警报。对于这个警报,我想创建SNS主题,以便在触发警报时向用户发送电子邮件。但使用publish,我可以立即发送,但我希望在触发/引发警报时发送电子邮件。有人可以指导我如何发送电子邮件时,报警触发一些发布消息。下面是我正在尝试的代码

import boto3,json
from sns_util import SNSUtil

def create_alarm_to_instances(file_name):
    # Iterate through each ec2_instance and create an alarm for the instance ID
    with open(file_name) as ip :
        ec2_instances = json.load(ip)
        for ec2_instance in ec2_instances:
            region = ec2_instance.get("region")
            instance_id = ec2_instance.get("instance_id")
            account_number = ec2_instance.get("account_number")
            cloudwatch = boto3.client('cloudwatch', region_name=region)
            email = ec2_instance.get("email").lower()
            topic_name = "CPU_Utilization"
            topic_arn = "arn:aws:sns:{}:{}:{}".format(region, account_number, topic_name)
            sns = SNSUtil(region=region)
            cloudwatch.put_metric_alarm(
                AlarmName='CPU_Utilization_%s' % instance_id,
                ComparisonOperator='LessThanThreshold',
                EvaluationPeriods=1,
                MetricName='CPUUtilization',
                Namespace='AWS/EC2',
                Period=60,
                Statistic='Average',
                Threshold=80.0,
                ActionsEnabled=True,
                AlarmActions=[topic_arn],
                AlarmDescription='Alarm raised when CPU is less than 40%',
                Dimensions=[
                    {
                        'Name': 'InstanceId',
                        'Value': instance_id
                    },
                ],
                Unit='Seconds'
            )
            print("Attached alarm to EC2 instance {} in the region {} ".format(instance_id,region))
            print("technical_owner is {} ".format(email))
            if not email.isspace():
                try:
                    # publish message when an alarm is raised only
                    sns.publish_sns(topic_arn=topic_arn, send_email=email, instance_id=instance_id)
                except Exception as e:
                    # sns.create_sns_topic(region=region, topic_name=topic_name)
                    sns.create_email_subscription(topic_arn=topic_arn, email_id=email)
                    print("Exception occurred while creating SNS Topic and below is the error \n{}".format(e))
            else:
                print("Technical owner is empty , hence not pulibshing/creating email subscription ")
            

if __name__ == '__main__':
    pass

sns_topic_publish


Tags: instancenameidformatgettopicisemail