Ref: https://learn.cantrill.io/courses/1820301/lectures/41301397


Protect an EC2 Instance if it gets Stopped

  1. Create a Lambda function that restarts an instance if it ever gets into the stopped state:
  2. Create a pattern matching rule in EventBridge
  3. Event to be tracked: EC2 Instance State-change Notification
  4. Recommended to generate a JSON sample of the event, to see what info is being delivered
  5. Fill out the event pattern to match EC2 instance moving to Stopped state:
  6. Specify the Lambda function that protects EC2 instances as target for the EventBridge rule:
  7. Test the rule by stopping an instance. After it is stopped, the instance should move back to Running state automatically after a while
  8. Logs from executed Lambda functions can be found in CWLogs → every Lambda function is a log group, and within it every execution is a log stream

Stop all EC2 Instances at a Specific Time Every Day

  1. Create a schedule rule in EventBridge
  2. With the new EventBridge Scheduler you have a more sophisticated UI and can specify schedules in multiple ways, even outside of event buses. With the traditional “Create Rule”, you could only specify the schedule in Unix CRON format, and the time HAD to be in UTC!
  3. Specify the schedule with a Unix CRON expression:
    1. ‼️ Careful with time zone! CRON is by default UTC, but the UI with EventBridge Scheduler might adapt it to your current time zone! Always check the “next triggers” to be sure configuration is correct!
  4. Select the Lambda function that stops instances as the target for this rule
  5. Wait for the specified time and observe how the instances are stopped. If the protection rule is still in place, the protected instances will then start running again after being stopped