CloudWatch Events

AWS Lambda supports CloudWatch Event Rules. This allows you to have a Lambda function run when there’s a change to AWS resources. Here’s an extensive list of supported Event Types.

An example might be getting notified when an unwanted security group port gets opened.

class SecurityJob < ApplicationJob
  events_rule(
    description: "Detects security group changes",
    event_pattern: {
      detail_type: ["AWS API Call via CloudTrail"],
      detail: {
        event_source: ["ec2.amazonaws.com"],
        event_name: [
          "AuthorizeSecurityGroupIngress",
          "AuthorizeSecurityGroupEgress",
          "RevokeSecurityGroupIngress",
          "RevokeSecurityGroupEgress",
          "CreateSecurityGroup",
          "DeleteSecurityGroup"
        ]
      }
    }
  )
  def detect_security_group_changes
    puts event # event is available
    # your logic
  end
end

You can further simplify the code with event_pattern. Here’s another example that detects when an instance goes into stopping state.

class SecurityJob < ApplicationJob
  event_pattern(
    source: ["aws.ec2"],
    detail_type: ["EC2 Instance State-change Notification"],
    detail: {
      state: ["stopping"],
    }
  )
  def instance_stopping
    # logic goes here
  end
end

This pattern of watching CloudWatch events can be used for things like automatically closing security group ports that get unintentionally opened. CloudWatch Events opens up a world of possibilities.

Multiple Events Support

Registering multiple events to the same Lambda function is supported. Add multiple event rules above the method definition. Example:

class SecurityJob < ApplicationJob
  event_pattern(
    source: ["aws.ec2"],
    detail_type: ["EC2 Instance State-change Notification"],
    detail: {
      state: ["stopping"],
    }
  )
  event_pattern(
    detail_type: ["AWS API Call via CloudTrail"],
    detail: {
      userIdentity: {
        type: ["Root"]
      }
    }
  )
  rate "10 hours"
  def perform_some_logic
    # logic goes here
  end
end

Notice in the above example that you can even mix in the rate declaration with the Lambda function. Underneath the hood rate delegates to the events_rule method.

Pro tip: Use the <- and -> arrow keys to move back and forward.

Edit this page

See a typo or an error? You can improve this page. This website is available on GitHub and contributions are encouraged and welcomed. We love pull requests from you!