看起来AWS不提供SMS作为美国东部以外的SNS主题订户的协议.我想连接我的CloudWatch警报并在出现故障时收到短信,但无法将其发送到SMS.
有没有办法做到这一点?
是!
经过一番挖掘,我能够让它发挥作用.它比仅选择一个主题或输入一个警报要复杂一点,但效果很好!
解决方案的关键是使用AWS的lambda函数!
数据流是这样的:
> Alarm triggered > -> Push notification to SNS > -> SNS posts to lambda > -> lambda reposts to SNS on us-east-1 > -> subscriber receives message
只是服务:
> CloudWatch Alarm (us-west-2) > -> SNS (us-west-2) > -> Lambda (us-west-2) > -> SNS (us-east-1) > -> SMS subscriber (us-east-1)
我不会过多地谈论设置SNS或设置lambda,你可以查看已经存在的示例.但是,我将分享我为执行此操作而编写的lambda代码.您可以使用发布消息到主题功能来测试它.
console.log('Loading function'); var Aws = require('aws-sdk'); var usEastSns = new Aws.SNS({ accessKeyId: "ENTER YOUR ACCESS KEY HERE", secretAccessKey: "ENTER YOUR SECRET KEY HERE", region: "us-east-1", logger: console }); exports.snsProxy = function(event, context) { var message = event.Records[0].Sns; console.log("received message: ", message); var newMessage = buildNewMessage(message); console.log("publishing: ", newMessage); usEastSns.publish(newMessage, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred } else { // It's important that we succeed in the callback // otherwise it seems to succeed without sending console.log(data); context.succeed(message); } }) }; function buildNewMessage(message) { // For some reason the message that gets sent in the event // does not contain the same interface as what the library // expects so it needs to be created return { TargetArn: "ENTER YOUR ARN IN US EAST HERE", Message: message.Message, Subject: message.Subject, MessageAttributes: collectAttr(message.MessageAttributes) }; } function collectAttr(attrs) { var newAttrs = {}; for (var attr in attrs) { newAttrs[attr] ={ DataType: attrs[attr].Type, StringValue: attrs[attr].Value } } return newAttrs; }
除了已经在lambda函数中的aws-sdk之外,这不需要任何其他库.如果您不想要它,您可以随意省略控制台日志记录,但它对调试很有用.
如果您使用测试功能,它可能会失败.我相信这是因为回调永远不会发生.
请记住,lambda不应该在us-east-1上,因为它将在你正在使用的任何区域被触发.
教程链接:
SNS发布api:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property
如何在lambda中使用node.js:
http://docs.aws.amazon.com/lambda/latest/dg/programming-model.html
关于使用其他aws函数的非常棒的教程:
http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html