I have updated my original post as have got a bit further and have the querying of my CW Alarms part of my code working. The below now outputs the state of my CW Alarms in the console, and in the format I want. What I’m now trying to do is take the output and upload this as a text file to an S3 bucket. Is this possible?
CW Alarm Code
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) {
}
};
Output
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
I have looked at the sdk for the s3 PutObjectCommand and have tested the below, which allows me to upload a file with some text content, but I’m not sure how I can combine my CW Alarm data with this code, so that the "Body" of the text file is my CW Alarm data.
S3 Code
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
export const handler = async() => {
const bucketName = "mybucket";
const keyName = "test.json";
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) {
}
};
Output
Function Logs
START RequestId: xxxxxxxxxxxxxxxxxxx Version: $LATEST
2022-11-30T09:56:45.585Z xxxxxxxxxxxxxxxxxxx INFO Successfully uploaded data to mybucket/test.json
END RequestId: xxxxxxxxxxxxxxxxxxx
My goal is to end up with the test.json file looking like this:
{"alarmname":"my-alarm-1","alarmstate":"OK"} {"alarmname":"my-alarm-2","alarmstate":"OK"}
Thanks.
2
Answers
With help from a colleague I have found the answer to this. As long as in your lambda function your index file is named "index.mjs"
You are using an outdated AWS SDK for JavaScript. Refer to the new AWS Code Library for the latest recommended SDK to use here:
URL is:
https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_cloudwatch_code_examples.html