How to check AWS EC2 instance current uptime

30.5k views Asked by At

What is the best way to check the EC2 instance uptime and possibly send alerts if uptime for instance is more then N hours? How can it be organized with default AWS tools such as CloudWatch, Lambda ?

3

There are 3 answers

5
helloV On BEST ANSWER

One option is to use AWS CLI and get the launch time. From that calculate the uptime and send it to Cloudwatch:

aws ec2 describe-instances --instance-ids i-00123458ca3fa2c4f --query 'Reservations[*].Instances[*].LaunchTime' --output text

Output

2016-05-20T19:23:47.000Z

Another option is to periodically run a cronjob script that:

  • calls uptime -p command
  • converts the output to hours
  • sends the result to Cloudwatch with dimension Count

After adding the cronjob:

  • add a Cloudwatch alarm that sends an alert when this value exceeds a threshold or if there is INSUFFICIENT DATA
  • INSUFFICIENT DATA means the machine is not up
1
Ben Fellows On

I would recommend looking into an "AWS" native way of doing this.

If it is basically sending OS level metrics (e.g. Free Memory, Uptime, Disk Usage etc...) to Cloudwatch then this can be achieved by following the guide: This installs the Cloudwatch Logs Agent on your EC2 instances. http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/QuickStartEC2Instance.html

The great thing about this is you then get the metrics show up in Cloudwatch logs (see attached picture which shows the CW Logs interface in AWS Console.).enter image description here

1
emorris On

Here's another option which can be done just in CloudWatch.

Create an alarm for your EC2 instance with something like CPUUtilization - you will always get a value for this when the instance is running.

  • Set the alarm to >= 0; this will ensure that whenever the instance is running, it matches.
  • Set the period and consecutive periods to match the required alert uptime, for example for 24 hours you could set the period to 1 hour and the consecutive periods to 24.
  • Set an action to send a notification when the alarm is in ALARM state.

Now, when the instance has been on less than the set time, the alarm will be in INSUFFICIENT DATA state. Once it has been on for the uptime, it will go to ALARM state and the notification will be sent.