amazon-web-services - 当 aws codebuild 完成时,将整个 cloudwatch 日志发送到 slack

标签 amazon-web-services aws-lambda amazon-cloudwatch aws-codepipeline aws-codebuild

我创建了一个 lambda 函数,用于将 codebuild cloudwatch 日志发送到 slack。它可以工作,但每次在 codebuild 运行时都会生成日志。它像垃圾邮件一样将消息扔到松弛的地方。

我只想在代码构建完成时发送一次完整的代码构建日志。

我不知道如何添加触发器,因为在 lambda 中我使用了 cloudwatch 触发器来让 lambda 工作。

cloudwatch logs trigger

Nodejs Lambda 函数

const zlib = require("zlib");
const https = require("https");
const SLACK_ENDPOINT ="/services/000000000000000000000000000000000000"
const SLACK_BOT = "deploy-notifications";

function doRequest(content) {
  // formatting the message according Slack API
  const payload = {
    username: SLACK_BOT,
    blocks: [
      {
        type: "header",
        text: {
          type: "plain_text",
          text: "Whoops, looks like something went wrong 😞🤕",
          emoji: true,
        },
      },
      {
        type: "section",
        fields: [
          {
            type: "mrkdwn",
            text: "<!here> the API is running into an issue",
          },
        ],
      },
      {
        type: "section",
        fields: [
          {
            type: "mrkdwn",
            text: "*Environment: * Production",
          },
        ],
      },
      {
        type: "section",
        fields: [
          {
            type: "mrkdwn",
            text: "*Message:* _" + content.message + "_",
          },
        ],
      },
      {
        type: "section",
        fields: [
          {
            type: "mrkdwn",
            text: "*Stacktrace:*",
          },
        ],
      },
      {
        type: "section",
        text: {
          type: "mrkdwn",
          text:
            "```" +
            JSON.stringify(content.original ? content.original : content) +
            "```",
        },
      },
      {
        type: "divider",
      },
    ],
  };

  const payloadStr = JSON.stringify(payload);
  const options = {
    hostname: "hooks.slack.com",
    port: 443,
    path: SLACK_ENDPOINT,
    channel: "#deploy-notifications",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Content-Length": Buffer.byteLength(payloadStr),
    },
  };

  const postReq = https.request(options, function (res) {
    const chunks = [];
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
      return chunks.push(chunk);
    });
    res.on("end", function () {
      if (res.statusCode < 400) {
        console.log("sent!!!");
      } else if (res.statusCode < 500) {
        console.error(
          "Error posting message to Slack API: " +
            res.statusCode +
            " - " +
            res.statusMessage
        );
      } else {
        console.error(
          "Server error when processing message: " +
            res.statusCode +
            " - " +
            res.statusMessage
        );
      }
    });
    return res;
  });
  postReq.write(payloadStr);
  postReq.end();
}

function main(event, context) {
  context.callbackWaitsForEmptyEventLoop = true;
  // always returns the last event
  const payload = Buffer.from(event.awslogs.data, "base64");
  const log = JSON.parse(zlib.gunzipSync(payload).toString("utf8"));
  // the log is an object that contains an array of events called `logEvents` and we need access it bypassing the index 0
  doRequest(log.logEvents[0]);
  const response = {
    statusCode: 200,
    body: JSON.stringify("Event sent to Slack!"),
  };
  return response;
}

exports.handler = main;

最佳答案

@abdullah 的回答应该可以解决您的问题。不过我会发布另一种方法

您只需启用 notifications on your build project 。您可以在构建状态或构建阶段配置所需的事件,并将此通知的目标配置为 sns。

在您的 sns 中订阅 lambda 即可。

您不必创建自定义事件规则或任何内容,只需在代码构建项目上配置事件通知规则即可。

如何配置通知:

  • 转到您的代码构建项目
  • 点击顶部的“通知”
  • 输入通知规则名称,选择您想要的事件并选择目标

enter image description here

注意: 我的回答假设您的 lambda 正在执行您打算执行的操作。

关于amazon-web-services - 当 aws codebuild 完成时,将整个 cloudwatch 日志发送到 slack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75896672/

相关文章:

amazon-web-services - Terraform 不会在 cloudwatch 事件目标上添加日志组名称

javascript - 通过 javascript 和凭证提供商进行身份验证的 AWS API 网关

amazon-web-services - 如何从自定义 REST API 将数据加载到 Redshift

amazon-web-services - 在AWS-ECS Docker容器上扩展根分区

python - 无法在 AWS Lambda 中显示信息级别日志记录

parallel-processing - 如果记录顺序不重要,我可以使用单个 Kinesis 分片并行调用 Lambda 函数吗?

amazon-web-services - 如何在用户数据中重新启动后运行多个 PowerShell 命令?

json - AWS Lambda http请求: Unable to stringify body as json: Converting circular structure to JSON

amazon-web-services - Cloudwatch Insights 在多行日志中搜索

amazon-web-services - 如何在CloudWatch中将值传递给Lambda函数?