Alert Creation for All VMs under same subscription in Azure using Terraform

1.5k views Asked by At
**I am trying to deploy below terraform alert for all VMs under my subscription, and subscription id I've kept it in variables file. But its throwing below error. 

Also how can I define type as MultipleResourceMultipleMetricCriteria for this below template as in ARM templates we can define this type as odata.type but when I try odata_type in terraform its not accepting it. also is there any way I can grab subscription id at runtime using query instead of passing subscription id in variables file. Is there any quickstart template site for the terraform for reference.

Error: **Can not parse "scopes.0" as a resource id: Cannot parse Azure ID: parse "{subscription_id is getting printed here}":** invalid URI for request**

  on metric.tf line 1, in resource "azurerm_monitor_metric_alert" "example":
   1: resource "azurerm_monitor_metric_alert" "example" {

terraform.tf file

resource "azurerm_monitor_metric_alert" "example" {
  name                = "example-metricalert"
  resource_group_name = "MyTemp"
  scopes              = ["${var.subscription_id}"]
  description         = "Action will be triggered when Transactions count is greater than 50."
  target_resource_type = "Microsoft.Compute/virtualMachines"
  
  criteria { 
    metric_namespace = "Microsoft.Compute/virtualMachines"
    metric_name      = "Percentage CPU"
    aggregation      = "Total"
    operator         = "GreaterThan"
    threshold        = 50
  }

  action {
    action_group_id = "/subscriptions/xxxxxxxx/resourceGroups/xxxxx/providers/Microsoft.Insights/actionGroups/xxxxx"
  }
}
1

There are 1 answers

7
Nancy On BEST ANSWER

You can use Data Source: azurerm_subscription to access information about an existing Subscription.

terraform.tf file will look like this:

data "azurerm_subscription" "current" {

  subscription_id  = var.subscription_id
}

resource "azurerm_monitor_metric_alert" "example" {
  name                = "example-metricalert"
  resource_group_name = "MyTemp"
  scopes              = [data.azurerm_subscription.current.id]
  description         = "Action will be triggered when Transactions count is greater than 50."
  target_resource_type = "Microsoft.Compute/virtualMachines"
  
  criteria { 
    metric_namespace = "Microsoft.Compute/virtualMachines"
    metric_name      = "Percentage CPU"
    aggregation      = "Total"
    operator         = "GreaterThan"
    threshold        = 50
  }

  action {
    action_group_id = "/subscriptions/xxxxxxxx/resourceGroups/xxxxx/providers/Microsoft.Insights/actionGroups/xxxxx"
  }
}