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!

gefragt vor 5 Jahren396 Aufrufe
2 Antworten
0
Akzeptierte Antwort

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

beantwortet vor 5 Jahren
0

That has worked perfectly! Thank you very much.

beantwortet vor 5 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen