jjzjj

amazon-web-services - 通过 Lambda 传递 Cloudwatch 数据 - Golang

coder 2024-07-07 原文

我正在努力实现以下目标:

  1. Lambda 由 Cloudwatch 警报触发
  2. Lambda 查看 Cloudwatch 收到的数据,并根据 NewStateValue
  3. 决定要做什么
  4. 如果需要,Lambda 将触发另一个 SNS,将所有 Cloudwatch 数据发送到 OpsGenie

我卡在了第三步。我可以通过手动指定来传递一些数据,但是,是否有一个函数可以将 Lambda 接收到的所有 JSON 传递到下一个 SNS?

我有 SNS、CloudWatch 警报和 CloudWatch 警报的消息部分的 JSON。

package main

import (
    "context"
    "fmt"
    "encoding/json"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"
)

func handler(ctx context.Context, snsEvent events.SNSEvent) {
    for _, record := range snsEvent.Records {
        snsRecord := record.SNS

//To add in additional fields to publish to the logs add "snsRecord.'fieldname'"
        fmt.Printf("Message = %s \n", snsRecord.Subject) 
        var event CloudWatchAlarmMessage

        err := json.Unmarshal([]byte(snsRecord.Message), &event)
        if err != nil {
            fmt.Println("There is an error: " + err.Error())
        }
        fmt.Printf("Test Message = %s \n", event.NewStateValue)
        // if ( event.Sns.Message.NewStateValue == "ALARM") {
        if ( event.NewStateValue == "ALARM") {
            svc := sns.New(session.New())
// params will be sent to the publish call included here is the bare minimum params to send a message.
    params := &sns.PublishInput{
        Message: aws.String(event.OldStateValue),
        Subject: aws.String(event.NewStateValue),
        TopicArn: aws.String("my arn"), //Get this from the Topic in the AWS console.
    }

    resp, err := svc.Publish(params)   //Call to puclish the message

    if err != nil {                    //Check for errors
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
        return
    }

    // Pretty-print the response data.
    fmt.Println(resp)
}
}


}
func main() {
    lambda.Start(handler)
}

我尝试使用 MessageStructure: aws.String("json"), 但它似乎只是导致 cannot use snsRecord (type events.SNSEntity) as type *string in字段值

根据我当前的设置,它成功发送了 NewStateValueOldStateValue

我目前可以访问的 JSON 结构:

package main

type SNS struct {
    Type              string    `json:"Type"`
    MessageID         string    `json:"MessageId"`
    TopicArn          string    `json:"TopicArn"`
    Subject           string    `json:"Subject"`
    Message           string    `json:"Message"`
    Timestamp         string `json:"Timestamp"`
    SignatureVersion  string    `json:"SignatureVersion"`
    Signature         string    `json:"Signature"`
    SigningCertURL    string    `json:"SigningCertURL"`
    UnsubscribeURL    string    `json:"UnsubscribeURL"`
    MessageAttributes struct {
        Alias struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"alias"`
        Entity struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"entity"`
        Tags struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"tags"`
        EventType struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"eventType"`
        Recipients struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"recipients"`
        Teams struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"teams"`
        Actions struct {
            Type  string `json:"Type"`
            Value string `json:"Value"`
        } `json:"actions"`
    } `json:"MessageAttributes"`
}

package main

type CloudWatchAlarms struct {
        Records []struct {
                EventVersion         string `json:"EventVersion"`
                EventSubscriptionArn string `json:"EventSubscriptionArn"`
                EventSource          string `json:"EventSource"`
                Sns                  struct {
                        Signature         string `json:"Signature"`
                        MessageID         string `json:"MessageId"`
                        Type              string `json:"Type"`
                        TopicArn          string `json:"TopicArn"`
                        MessageAttributes struct {
                        } `json:"MessageAttributes"`
                        SignatureVersion string    `json:"SignatureVersion"`
                        Timestamp        string `json:"Timestamp"`
                        SigningCertURL   string    `json:"SigningCertUrl"`
                        Message          string    `json:"Message"`
                        UnsubscribeURL   string    `json:"UnsubscribeUrl"`
                        Subject          string    `json:"Subject"`
                } `json:"Sns"`
        } `json:"Records"`
}

package main

type CloudWatchAlarmMessage struct {
    AlarmName        string `json:"AlarmName"`
    AlarmDescription string `json:"AlarmDescription"`
    AWSAccountID     string `json:"AWSAccountId"`
    NewStateValue    string `json:"NewStateValue"`
    NewStateReason   string `json:"NewStateReason"`
    StateChangeTime  string `json:"StateChangeTime"`
    Region           string `json:"Region"`
    OldStateValue    string `json:"OldStateValue"`
    Trigger          struct {
        MetricName    string      `json:"MetricName"`
        Namespace     string      `json:"Namespace"`
        StatisticType string      `json:"StatisticType"`
        Statistic     string      `json:"Statistic"`
        Unit          interface{} `json:"Unit"`
        Dimensions    []struct {
            Name  string `json:"name"`
            Value string `json:"value"`
        } `json:"Dimensions"`
        Period                           int    `json:"Period"`
        EvaluationPeriods                int    `json:"EvaluationPeriods"`
        ComparisonOperator               string `json:"ComparisonOperator"`
        Threshold                        float64    `json:"Threshold"`
        TreatMissingData                 string `json:"TreatMissingData"`
        EvaluateLowSampleCountPercentile string `json:"EvaluateLowSampleCountPercentile"`
    } `json:"Trigger"`
}

如果有人有任何见解,将不胜感激。

谢谢。

最佳答案

如果我对你的问题的理解正确,那么你正在尝试捕捉一个 cloudwatch 事件,如果满足特定条件,你想向 SNS 发送消息。我相信下面的代码可能会有所帮助,它是一个在 cloudwatch 事件上触发的 lambda,它在满足条件时向 sns 发送消息

import(
  "context"
  "github.com/aws/aws-sdk-go/aws"
  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-lambda-go/lambda"
  "github.com/aws/aws-sdk-go/aws/session"
  "github.com/aws/aws-sdk-go/service/sns"
)
//React to cloudwatch events
func handler(ctx context.Context, cloudWatchEvent events.CloudWatchEvent) error {
  //In case event met your conditions
  if string(cloudWatchEvent.Detail) == "Detail you expect to trigger sns" {
    //create session for sns service
    sess := session.New()
    //init sns service
    snsService := sns.New(sess)
    //publish message to sns
    snsService.Publish(&sns.PublishInput{
        Message:  aws.String("Your message"), //you can marshall the cloudwatch event here
        TopicArn: aws.String("your sns topic"),
    })
    //handle error/success here
    if err != nil {
        log.Print(err)
    } else {
        log.Printf("Message %s sent", output.MessageId)
    }
  }
  return nil
}

func main() {
  lambda.Start(handler)
}

希望这能给你一些帮助:)

关于amazon-web-services - 通过 Lambda 传递 Cloudwatch 数据 - Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52447549/

有关amazon-web-services - 通过 Lambda 传递 Cloudwatch 数据 - Golang的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  4. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  7. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  8. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  9. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  10. 通过 MacPorts 的 RubyGems 是个好主意吗? - 2

    从MB升级到新的MBP后,Apple的迁移助手没有移动我的gem。我这次是通过macports安装ruby​​gems,希望在下次升级时避免这种情况。有什么我应该注意的陷阱吗? 最佳答案 如果你想把你的gems安装在你的主目录中(在传输过程中应该复制过来,作为一个附带的好处,会让你以你自己的身份运行geminstall,而不是root),将gemhome:键设置为您在~/.gemrc中的主目录中的路径. 关于通过MacPorts的RubyGems是个好主意吗?,我们在StackOverf

随机推荐