A pure NodeJS function to kill select EC2 instances if they run longer than a defined period.
This is useful as a safety measure when using EC2 in CI and launching many instances.
A CI crash or user action could prevent proper cleanup, leaving expensive machines running forever
(or until the next billing cycle when there is much screaming).
You will need the following privileges in your AWS role:
- EC2 - describe, terminate
- Lambda - probably most of them
- EventBridge - read/write.
- CloudWatch - probably read.
- Create a from-scratch Lambda function
- In the new role, add full control on EC2
- Paste the javascript code, adjust config (top), click Deploy, then Test and see how it works.
- Under
Configuration->Triggers
, create a new EventBridge trigger. Example cron expression:cron(0 * * * ? *)
- Create a small instance with the matching tag(s).
- Click Test. If enough time elapsed (maxAge), it should be terminated. You can lower maxAge temporarily, deploy, test.
- Create another instance
- Wait for the cron to run.