Create an alert when the CPU usage of a virtual machine exceeds a certain percentage.
You can use the below code to create an alert rule using Azure java sdk.
Code:
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.monitor.models.MetricAlert;
import com.azure.resourcemanager.monitor.models.MetricAlertRuleCondition;
import com.azure.resourcemanager.monitor.models.MetricAlertRuleTimeAggregation;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.AzureResourceManager;
import java.time.Duration;
public final class App {
public static boolean runSample(com.azure.resourcemanager.AzureResourceManager azureResourceManager) {
String rgName="your-resourcegrp";
MetricAlert ma = azureResourceManager.alertRules().metricAlerts().define("Critical performance alert")
.withExistingResourceGroup(rgName)
.withTargetResource("/subscriptions/xxxxx/resourceGroups/xxxproviders/Microsoft.Compute/virtualMachines/vm678")
.withPeriod(Duration.ofMinutes(5))
.withFrequency(Duration.ofMinutes(1))
.withAlertDetails(3, "This alert rule is for U5 - Single resource-multiple criteria - with dimensions - with star")
.withActionGroups("/subscriptions/xxxxxx/resourceGroups/xxxx/providers/microsoft.insights/actiongroups/actiongroup1")
.defineAlertCriteria("Metric1")
.withMetricName("Percentage CPU")
.withCondition(MetricAlertRuleTimeAggregation.TOTAL, MetricAlertRuleCondition.GREATER_THAN, 80)
.attach()
.create();
return true;
}
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
.build();
AzureResourceManager azureResourceManager = AzureResourceManager
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withSubscription("your-subscription-id");
// Print selected subscription
System.out.println("Selected subscription: " + azureResourceManager.subscriptionId());
runSample(azureResourceManager);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Alert rule created..");
}
}
Output:
Selected subscription: xxxxxxxx
Alert rule created..

Portal:
The above code was executed and created an alert rule successfully for the virtual machine.

Reference:
Monitor-java-metric-alerts-on-critical-performance · GitHub