AWS - Using CloudWatch to trigger script on ec2 instance

5.4k views Asked by At

I've found a lot of similar questions but none that seem to be specific to my question here: I have a python script that deletes old log files. I have Cloudwatch to monitor available storage, is it possible to trigger that script (IE, run this command: python mypythonscript.py) when alarm is triggered.

From all my research this does not appear to be possible unless we developed a system that interpreted the emails sent by CloudWatch and SNS and then run a script based on that interpretation.

The goal is self-healing this issue when it alarms, but from what we've gathered it doesn't appear to be possible that CloudWatch itself can trigger anything to happen on the EC2 instance. If this is true, I'm just looking for confirmation from people smarter than I!

Thanks!

3

There are 3 answers

1
Mark B On BEST ANSWER

CloudWatch, by itself, cannot run a command on your EC2 instance. You could however combine CloudWatch with some other AWS services to accomplish your goal. The way I would recommend accomplishing this is the following:

0
Zachary Ryan Smith On

To expand on @Viviane's answer: Create an EventBridge event. Have it trigger off a custom event pattern to match your CloudWatch events of interest (these events are auto-pub'd to EventBridge). These links helped me:

0
Viviane On

Or you can use

CloudWatch Events for execute Run Command:

https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-cwe.html