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!

asked 5 years ago391 views
2 Answers
0
Accepted Answer

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

answered 5 years ago
0

That has worked perfectly! Thank you very much.

answered 5 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions