AWS为Lambda创建Cloudformation日志警报

时间:2017-08-16 04:17:48

标签: amazon-web-services aws-lambda amazon-cloudformation amazon-sns amazon-cloudwatch

我想在Lambda函数出现问题时创建警报,特别是当lambda抛出异常时。我打算配置SNS主题,以便在触发该警报时发送消息。

所有lambda都是使用CloudFormation脚本创建的,因此我正在搜索CloudFormation模板以配置CloudWatch日志的警报。我无法找到好的/可行的样本。示例代码如下。

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "AWS CloudTrail API Activity Alarm Template for CloudWatch Logs",
  "Parameters" : {
      "LogGroupName" : {
          "Type" : "String",
          "Default" : "CloudTrail/DefaultLogGroup",
          "Description" : "Enter CloudWatch Logs log group name. Default is CloudTrail/DefaultLogGroup"
      },
      "Email" : {
          "Type" : "String",
          "Description" : "Email address to notify when an API activity has triggered an alarm"
      }
  },
  "Resources" : {
    "SecurityGroupChangesAlarm": {
      "Type": "AWS::CloudWatch::Alarm",
      "Properties": {
          "AlarmName" : "CloudTrailSecurityGroupChanges",
          "AlarmDescription" : "Alarms when an API call is made to create, update or delete a Security Group.",
          "AlarmActions" : [{ "Ref" : "AlarmNotificationTopic" }],
          "MetricName" : "SecurityGroupEventCount",
          "Namespace" : "CloudTrailMetrics",
          "ComparisonOperator" : "GreaterThanOrEqualToThreshold",
          "EvaluationPeriods" : "1",
          "Period" : "300",
          "Statistic" : "Sum",
          "Threshold" : "1"
      }
    },

    "AlarmNotificationTopic": {
      "Type": "AWS::SNS::Topic",
      "Properties": {
          "Subscription": [
              {
                  "Endpoint": { "Ref": "Email" },
                  "Protocol": "email"
              }
          ]
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

为了做到这一点,我们需要使用FilterPattern在该lambda的日志组上创建一个订阅过滤器:“Exception”

因此,只要日志消息中有异常字,它就会触发监视器lambda。

以下是我写的YAML中的一个云形态模板

Resources:
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      Policies:
        - PolicyName: 'AllowLambdaAccess'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Effect: "Allow"
                Resource:
                  Fn::Join:
                    - ''
                    - - 'arn:aws:logs:'
                      - Ref: AWS::Region
                      - ':'
                      - Ref: AWS::AccountId
                      - ':log-group:/aws/lambda/*'
              - Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                Effect: "Allow"
                Resource: "*"
      RoleName: !Sub "${AWS::StackName}-LambdaExecutionRole"
  SubscriptionFilter: 
    Type: "AWS::Logs::SubscriptionFilter"
    DependsOn: "LambdaInvokePermission"
    Properties: 
      LogGroupName: !Sub "/aws/lambda/${LogGroupName}"
      FilterPattern: "Exception"
      DestinationArn: 
        Fn::GetAtt: 
          - "LambdaFunction"
          - "Arn"
  LambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Code:
        S3Bucket: !Ref S3BucketName
        S3Key: !Ref ZipFile
      Description: Monitor Lambda Function
      Handler: 'index.handler'
      MemorySize: 1536
      Role: !GetAtt 
        - LambdaExecutionRole
        - Arn
      Runtime: nodejs6.10  
      Environment:
        Variables:
          SMTP_SERVER: !Ref SMTPServer
          SMTP_PORT: !Ref SMTPPort
          EMAIL_FROM: !Ref FromEmail
          EMAIL_TO: !Ref ToEmail
      Timeout: 300
      FunctionName: !Sub "${AWS::StackName}-LambdaFunction"
      VpcConfig:
        SecurityGroupIds: !Split [ ",", !Ref SecurityGroupId ]
        SubnetIds: !Split [ ",", !Ref SubnetIds ]
    DependsOn:
      - LambdaExecutionRole
  LambdaInvokePermission: 
      Type: AWS::Lambda::Permission
      Properties:
        FunctionName: !Ref "LambdaFunction"
        Action: "lambda:InvokeFunction"
        Principal: !Sub "logs.${AWS::Region}.amazonaws.com"
        SourceArn:  
            Fn::Join:
                - ''
                - - 'arn:aws:logs:'
                  - Ref: AWS::Region
                  - ':'
                  - Ref: AWS::AccountId
                  - !Sub ':log-group:/aws/lambda/${LogGroupName}*'