I think it is a basic and amateur question, but I am trying to write a Lambda function on AWS which gets the stop-time tag I have defined on an EC2 instance and check it everyday and send me a reminder email 24 hours before reaching that time. The reminder email I have fixed, I know who to track change in the state of an EC2 AFTER it stops or starts but I am not sure how should I approach the first part which is getting the stop-time tag and notify me 24 hours BEFORE its stop-time. thanks
- 1How precise do you want the reminder email time to be? That is, do you want it to be exactly 24 hours before or it could be a few hours before or after? A way I can think of is using CloudWatch event to trigger a Lambda periodically and check for instances to be stopped between a specific period. Precision would depend on how frequent the function is scheduled to run, ex. if run every 24 hours, email would need to be sent out 24-48 hours before.Paradigm– Paradigm2020-06-03 14:43:09 +00:00Commented Jun 3, 2020 at 14:43
- well I prefer it to be 24 hours but it is not a strict requirement, so the periodic approach you mentioned also works for me.shahab4ai– shahab4ai2020-06-03 16:58:15 +00:00Commented Jun 3, 2020 at 16:58
- 1Here are some stopinators that do something similar: Simple EC2 Stopinator in Lambda - DEV Community 👩💻👨💻John Rotenstein– John Rotenstein2020-06-04 08:00:24 +00:00Commented Jun 4, 2020 at 8:00
1 Answer
You can implement this use-case using scheduling Lambda functions to run at a defined interval with CloudWatch Events: Documentation
Basic overview:
Decide how precisely you want your email to be sent out, this would also be how frequently your Lambda function to send the email will need to be run. Example: If you are okay with the email being sent out 24-36 hours before EC2 instance termination, the Lambda function would need to run at 12 hours intervals.
Based on the number you decide, say
xhours, your Lambda function code would need to check if there are any instances set to stop in the nextxhours from now. If any instances found, use SES to send out an email.Schedule this function to be invoked every
xhours using CloudWatch Events (doc)
For error handling, you can set an additional tag for the EC2 instances when the email has been sent out for it. So, if for some reason the Lambda function fails to be invoked and the instance will stop in <24 hours, this tag would tell you if the email was sent out or not.