Last active
August 15, 2022 08:37
-
-
Save f9n/d7acfb861766210a4b291e3e22012093 to your computer and use it in GitHub Desktop.
Undefined ec2 instance name alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In 2019 | |
import os | |
import json | |
import time | |
import boto3 | |
TOPIC_NAME = os.getenv("TOPIC_NAME", "FatihMail") | |
SLEEP_TIME = os.getenv("SLEEP_TIME", 300) | |
def get_instance_tag_value(instance, key_name="Name"): | |
print("[+] get_instance_tag_value() ") | |
for tag in instance.tags: | |
if tag["Key"] == key_name: | |
return tag["Value"] | |
return None | |
def get_instance_name(instance_id): | |
print("[+] get_instance_name() ") | |
ec2 = boto3.resource("ec2") | |
instance = ec2.Instance(instance_id) | |
return get_instance_tag_value(instance) | |
def handle(event, context): | |
region = event["region"] | |
account = event["account"] | |
instance_event_state = event["detail"]["state"] | |
instance_id = event["detail"]["instance-id"] | |
topic_arn = f"arn:aws:sns:{region}:{account}:{TOPIC_NAME}" | |
if instance_event_state == "running": | |
time.sleep(SLEEP_TIME) | |
instance_name = get_instance_name(instance_id) | |
print(f"InstanceName: {instance_name}") | |
if instance_name is None: | |
subject = "Undefined Ec2 Instance Name" | |
message = f"InstanceId: {instance_id}" | |
# Create an SNS client | |
sns_client = boto3.client("sns") | |
# Publish a simple message to the specified SNS topic | |
response = sns_client.publish( | |
TopicArn=topic_arn, Subject=subject, Message=message | |
) | |
print(response) | |
else: | |
print("[+] Undefined Ec2 Istance Event State") | |
return {"statusCode": 200, "body": json.dumps("Undefined Ec2 Instance Name!")} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment