AWS实现自动监控新服务

admin 2025年5月23日16:01:39评论0 views字数 4309阅读14分21秒阅读模式
最近收到一个新需求,emmmmm,想要做一个监控,监控AWS上付费新服务的开启,为啥会有这样的需求呢,主要还是业务在不断的增加,云上资源的管理也越发力不从心,领导看着步步高升的费用,着实心痛,所以需求就来了。
AWS实现自动监控新服务
话不多说,直接上正文。实现比较简单,也就是使用eventbridge来实时获取付费服务创建事件,然后使用lambda将消息钉出来。
开干,直接上代码。
AWS实现自动监控新服务
eventbridge主要代码如下。
resource "aws_cloudwatch_event_rule" "new_service_alert" {  name        = "new-service-alert"  description = "Trigger Lambda on new service creation or enabling"  event_pattern = jsonencode({    "source" : [      "aws.ec2""aws.rds""aws.config""aws.guardduty",      "aws.securityhub""aws.inspector2""aws.eks""aws.elasticloadbalancing",      "aws.cloudtrail""aws.cloudwatch""aws.ssm""aws.marketplace""aws.backup","aws.billingconsole"    ],    "detail-type" : ["AWS API Call via CloudTrail"],    "detail" : {      "eventName" : [        { "prefix" : "Enable" },        { "prefix" : "Create" },        { "prefix" : "Activate" },        "AcceptInvitation",        "EnableOrganizationAdminAccount",        "PurchaseReservedInstancesOffering",        "SubscribeToEvent",        "RunInstances",        "LaunchInstances"      ]    }  })}resource "aws_lambda_permission" "allow_eventbridge" {  statement_id  = "AllowExecutionFromEventBridge"  action        = "lambda:InvokeFunction"  function_name = aws_lambda_function.alert_handler.function_name  principal     = "events.amazonaws.com"  source_arn    = aws_cloudwatch_event_rule.new_service_alert.arn}resource "aws_cloudwatch_event_target" "lambda_target" {  rule      = aws_cloudwatch_event_rule.new_service_alert.name  target_id = "InvokeLambda"  arn       = aws_lambda_function.alert_handler.arn}
lambda函数代码如下。
data "archive_file" "lambda_zip" {  type        = "zip"  source_dir  = "${path.module}/lambda"  output_path = "${path.module}/lambda.zip"}resource "aws_lambda_function" "alert_handler" {  function_name = "new_service_alert_handler"  runtime       = "nodejs18.x"  handler       = "index.handler"  role          = aws_iam_role.lambda_exec_role.arn  filename         = data.archive_file.lambda_zip.output_path  source_code_hash = data.archive_file.lambda_zip.output_base64sha256}
lambda运行的js逻辑代码如下,也就是通知代码。
onst https = require('https');const DINGTALK_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=?";exports.handler = async (event) => {    console.log('Received event:'JSON.stringify(event, null2));    // 获取事件相关的信息const service = event.detail?.eventName || 'UnknownEvent';const eventTime = detail.eventTime || new Date().toISOString();    const sourceService = event.source || 'UnknownSource';    const identity = event.detail?.userIdentity || {};    const user = identity.arn || identity.principalId || 'UnknownUser';    const ignoredUser = identity.sessionContext?.sessionIssuer?.userName || 'UnknownUser';    const time = event.time || new Date().toISOString();    const region = event.region || 'UnknownRegion';    const consoleLink = `https://console.aws.amazon.com/cloudtrail/home?region=${region}#/events`;    const ignoredRoles = ['AWSServiceRoleForECS']; //添加忽略的role    if (ignoredRoles.some(role => ignoredUser.includes(role))) {        console.log('Ignored event from AWS service role:', ignoredUser);        return;    }    const ignoredServices = ['CreateLaunchTemplate']; //添加忽略的服务事件    if (ignoredServices.some(ignoredService => service.includes(ignoredService))) {        console.log('Ignored event from AWS service event:', service);        return;    }    const message = {        msgtype"markdown",        markdown: {            title"⚠️新服务启用警告",            text:                `### ⚠️AWS新服务启用警告n` +                `- **事件类型**: ${service}n` +                `- **来源服务**: ${sourceService}n` +                `- **操作者**: ${user}n` +                `- **时间**: ${eventTime}nn` +                `点击查看事件详情(CloudTrail)](${consoleLink})`  }};    // 发送钉钉消息    const sendMessage = (data) => {        return new Promise((resolve, reject) => {            const req = https.request(DINGTALK_WEBHOOK, {                method'POST',                headers: {                    'Content-Type''application/json'                }            }, (res) => {                let body = '';                res.on('data'(chunk) => {                    body += chunk;                });                res.on('end'() => {                    resolve(body);                });            });            req.on('error'(error) => {                reject(error);            });            req.write(JSON.stringify(data));            req.end();        });    };    try {        const response = await sendMessage(message);        console.log('Message sent to DingTalk:', response);    } catch (error) {        console.error('Error sending message to DingTalk:', error);    }};
主要逻辑代码就这些,剩下的就是lambda运行想要的权限声明,这里就不多做赘述。差不多实现效果如下(有付费服务开启,就会立马钉到指定群里,看看是那位小可爱在花钱)。
AWS实现自动监控新服务

原文始发于微信公众号(安全无界):AWS实现自动监控新服务

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2025年5月23日16:01:39
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   AWS实现自动监控新服务https://cn-sec.com/archives/4083637.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息