HandleGuardDutyFinding
Navigate to the AWS Lambda Console to begin creating a new Lambda function.
HandleGuardDutyFinding
.lambda_function.py
file.import json
import boto3
# Initialize AWS clients
ec2 = boto3.client('ec2')
sns = boto3.client('sns')
# Define your target EC2 instance ID and SNS topic ARN
import boto3
import json
# Tạo client EC2 và SNS từ AWS SDK
ec2 = boto3.client('ec2')
sns = boto3.client('sns')
# ID của instance EC2 và ARN của SNS Topic
INSTANCE_ID = ''
SNS_TOPIC_ARN = ''
def lambda_handler(event, context):
# In thông tin sự kiện GuardDuty nhận được
print("GuardDuty Event:")
print(json.dumps(event, indent=2))
# Gửi thông báo qua SNS
sns.publish(
TopicArn=SNS_TOPIC_ARN,
Subject='GuardDuty Alert',
Message=f'GuardDuty detected suspicious behavior. Stopping EC2: {INSTANCE_ID}'
)
# Dừng instance EC2 có ID đã chỉ định
ec2.stop_instances(InstanceIds=[INSTANCE_ID])
# Trả về kết quả sau khi thực hiện các hành động
return {
'statusCode': 200,
'body': json.dumps('EC2 has been stopped and an email alert has been sent.')
}