Help with AWS Lambda function to send notifications

0

Hello there,

Thanks in advance for your comments. I am really a beginner in Python and I would really appreciate your help.

I need to create an AWS Lambda function to send a notification every four hours if a specific instance is up and running. I have created the code below, but that does not work at all (I know that probably is very bad code :)). Could you please advise? I would use an AWS CloudWatch event as trigger and an AWS SNS topic to send the notification.

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,

Thanks!

已提問 5 年前檢視次數 396 次
2 個答案
0
已接受的答案

Hi,
Here is one way to write your AWS Lambda function:

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 ''

Hope this helps!
-randy

已回答 5 年前
0

That has worked perfectly! Thank you very much.

已回答 5 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南