【问题标题】:Use AWS Lambda to get CloudWatch Alarm States使用 AWS Lambda 获取 CloudWatch 警报状态
【发布时间】:2022-11-30 18:28:09
【问题描述】:

我已经更新了我的原始帖子,因为它更进一步,并且我的代码中的 CW 警报查询部分可以正常工作。下面现在在控制台中以我想要的格式输出我的 CW 警报的状态。我现在要做的是获取输出并将其作为文本文件上传到 S3 存储桶。这可能吗?

CW 警报代码

import { CloudWatchClient, DescribeAlarmsCommand } from "@aws-sdk/client-cloudwatch";
const REGION = "eu-west-2";

const cwclient = new CloudWatchClient({ region: REGION });

export const handler = async() => {
  
const cwparams = {};
const cw = new DescribeAlarmsCommand(cwparams);

try {
  const cwdata = await cwclient.send(cw);
  cwdata.MetricAlarms.forEach(function (item) {
      console.log('\n%j', {alarmname:item.AlarmName,alarmstate:item.StateValue})
    });
  
} catch (error) {

  }
}

输出

Function Logs
START RequestId: xxxxxxxxxxxxxxxxxxx Version: $LATEST
2022-11-30T09:48:34.655Z    xxxxxxxxxxxxxxxxxxx INFO    
{"alarmname":"my-alarm-1","alarmstate":"OK"}
2022-11-30T09:48:34.655Z    xxxxxxxxxxxxxxxxxxx INFO    
{"alarmname":"my-alarm-2","alarmstate":"OK"}
END RequestId: xxxxxxxxxxxxxxxxxxx

我查看了 s3 PutObjectCommand 的 sdk 并测试了下面的内容,它允许我上传包含一些文本内容的文件,但我不确定如何将我的 CW 警报数据与此代码结合起来,以便“文本文件的正文是我的 CW 警报数据。

S3代码

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
const REGION = "eu-west-2";

const s3client = new S3Client({ region: REGION });

export const handler = async() => {

const bucketName = "mybucket"
const keyName = "test.txt"

const s3 = new S3Client({})

const s3putCommand = new PutObjectCommand({
  Bucket: bucketName,
  Key: keyName,
  Body: "Hello"  // I would like this to be my CW Alarm data
})

try {
    await s3.send(s3putCommand)
    console.log('Successfully uploaded data to ' + bucketName + '/' + keyName)
  
} catch (error) {
  
  }
}

输出

Function Logs
START RequestId: xxxxxxxxxxxxxxxxxxx Version: $LATEST
2022-11-30T09:56:45.585Z    xxxxxxxxxxxxxxxxxxx INFO    Successfully uploaded data to mybucket/test.txt
END RequestId: xxxxxxxxxxxxxxxxxxx

我的目标是最终得到如下所示的 text.txt 文件:

{"alarmname":"my-alarm-1","alarmstate":"OK"} {"alarmname":"my-alarm-2","alarmstate":"OK"}

谢谢。

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda


    【解决方案1】:

    您使用的是过时的适用于 JavaScript 的 AWS 开发工具包。参考新的AWS 代码库最新推荐的 SDK 在这里使用:

    网址是:

    https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_cloudwatch_code_examples.html

    【讨论】:

    • 啊,谢谢你。我仍然在让它工作时遇到一些麻烦,但会更多地关注更新版本。
    • 我已经用我的进步和我最后的挑战更新了原来的帖子。希望有人可以帮助我以我想要的方式进行这项工作。
    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 2021-10-03
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多