Search code examples
azurevirtual-machinealertcost-management

Alert for Azure Virtual Machine running for X hours?


I use an Azure VM for personal purposes and use it mostly like I would use a laptop for checking email etc. However, I have several times forgot to stop the VM when I am done using it and thus have had it run idle for days, if not weeks, resulting in unnecessarily high billing.

I want to set up an email (and if possible also SMS and push notification) alert.

I have looked at the alert function in the advisor, but it does not seem to have enough customization to handle such a specific alert (which would also reduce Microsoft's income!).

Do you know any relatively simple way to set up such an alert?


Solution

  • You can take use of Log Analytics workspaces and Custom log search.

    The below are the steps to create an alert, which will send the alert if the azure vm is running exactly 1 hour.

    First:

    you need to create a Log Analytics workspaces and connect to azure vm as per this link.

    Sencod:

    1.In azure portal, nav to Azure Monitor -> Alerts -> New alert rule.

    2.In the "Create rule" page, for Resource, select the Log Analytics workspaces you created ealier. Screenshot as below:

    enter image description here

    Then for Condition, please select Custom log search. Screenshot as below:

    enter image description here

    Then in the Configure signal logic page, in Search query, input the following query:

    Heartbeat
    | where Computer == "yangtestvm" //this is your azure vm name
    | order by TimeGenerated desc 
    

    For Alert logic: set Based on as Number of results, set Operator as Equal to, set Threshold value as 60.

    For Evaluated based on: set Period as 60, set Frequency as 5.

    The screenshot as below:

    enter image description here

    Note:

    for the above settings, I query the Heartbeat table. For azure vm which is running, it always sends data to log analytics to the Heartbeat table per minute. So if I want to check if the azure vm is running exactly 1 hour(means it sends 60 data to Heartbeat table), just use the above query, and set the Threshold value to 60.

    Another thing is the Period, it also needs to be set as 1 hour(60 minutes) since I just check if the azure vm is running for 1 hour; for Frequecy, you can set it any value you like.

    If you understand what I explains, you can change these values as per your need.

    At last, set the other settings for this alert.

    Please let me know if you still have more issues about this.