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년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠