帮助编写AWS Lambda函数以发送通知。

0

【以下的问题经过翻译处理】 你好,

提前感谢您的评论。我真的是一个Python的初学者,非常感谢您的帮助。

我需要创建一个AWS Lambda函数,以便在特定实例正在运行的情况下每隔四个小时发送一次通知。我已经创建了下面的代码,但这根本不起作用(我知道可能是非常糟糕的代码 :))。请问您能否建议一下吗?我将使用AWS CloudWatch事件作为触发器和AWS SNS主题发送通知。

import boto3

def instance_status(event, context): try: client = boto3.client('ec2') r = client.describe_instance_status(InstanceIds=['i-xxxxxxxxxx']) if r == 16: sns = boto3.client('sns') response = sns.publish( TopicArn='arn:aws:sns:us-east-1:xxxxxxx:xxxxxxx', Message='The x instance is up and running', ) regards,

谢谢!

profile picture
专家
已提问 5 个月前9 查看次数
1 回答
0

【以下的回答经过翻译处理】 你好,

以下是编写AWS Lambda函数的一种方法:

import boto3
def lambda_handler(event, context):
    INSTANCE_ID = 'i-05c69a91775e1258b'
    TARGET_ARN = 'arn:aws:sns:us-east-1:xxxxxxxx:MyEmailTopic'
    
    ec2_client=boto3.client('ec2')
    sns_client=boto3.client('sns')
    instances = ec2_client.describe_instance_status(InstanceIds=[INSTANCE_ID])
    instance_state = instances["InstanceStatuses"][0]["InstanceState"]["Name"]
    if(instance_state=="running"):
        response = sns_client.publish(
            TargetArn=TARGET_ARN,
            Message="The " + INSTANCE_ID + " instance is up and running"
        )
    else:
        print("failed to get status")
    return ''

希望能对你有所帮助!

-randy

profile picture
专家
已回答 5 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则