How to create alert rule in terraform for SQL DB - azure

I can't seem to find any examples and I am running into different errors depending on what I'm doing.
I'm trying to get this to work and it's just not happening... any thoughts?
resource "azurerm_monitor_metric_alert" "example" {
name = "example-metricalert"
resource_group_name = azurerm_resource_group.example.name
scopes = [azurerm_mssql_database.test.server_id]
description = "Action will be triggered when cpu is greater than 80%."
criteria {
metric_namespace = "Microsoft.Sql/servers/databases"
metric_name = "CPU_percentage"
aggregation = "Average"
operator = "GreaterThan"
threshold = 80
}
}

You can use the below code to create an metrics alert for SQL DB. I have tested it for an existing SQL DB, so used data blocks.
Main.tf
provider "azurerm" {
features {}
}
data "azurerm_mssql_server" "example" {
name = "ztestansumanserver"
resource_group_name = "yourresourcegroup"
}
data "azurerm_mssql_database" "dbtomonitor" {
name = "testansumandb"
server_id = data.azurerm_mssql_server.example.id
}
resource "azurerm_monitor_action_group" "example" {
name = "CriticalAlertsAction"
resource_group_name = data.azurerm_mssql_server.example.resource_group_name
short_name = "p0action"
email_receiver {
name = "sendtoadmin"
email_address = "youremailid"
use_common_alert_schema = true
}
}
resource "azurerm_monitor_metric_alert" "example" {
name = "example-metricalert"
resource_group_name = data.azurerm_mssql_server.example.resource_group_name
scopes = [data.azurerm_mssql_database.dbtomonitor.id]
description = "Action will be triggered when cpu percent is greater than 80."
criteria {
metric_namespace = "Microsoft.Sql/servers/databases"
metric_name = "cpu_percent"
aggregation = "Average"
operator = "GreaterThan"
threshold = 80
}
action {
action_group_id = azurerm_monitor_action_group.example.id
}
}
output:
Note: As per the above script alert is created successfully and it will also trigger a mail to you when the cpu_percent > 80 .
Reference:
Azure Monitor supported metrics by resource type - Azure Monitor | Microsoft Docs

Related

auto scale azure spring app URI with terraform

I need enable auto scale for an spring app hosted by spring app services.I am used below terraform code.
resource "azurerm_monitor_autoscale_setting" "spring_apps_app_carrier_events" {
name = "default_auto_scale"
enabled = true
resource_group_name = module.rg.resource_group_name
location = module.rg.resource_group_location
target_resource_id = module.spring_apps_app_carrier_events.app_identities[0].principal_id
profile {
name = "defaultProfile"
capacity {
default = 1
minimum = 1
maximum = 2
}
It return errors:
Error: Can not parse "target_resource_id" as a resource id: Cannot parse Azure ID: parse "290dc6bd-1895-4e52-bac2-a34e63a138a9": invalid URI for request
It seems it need a uri. May u know how can I get the uri of a spring app?
Thanks in advance
I tried to reproduce the same in my environment.
Received the same error:
│ Error: Can not parse "target_resource_id" as a resource id: Cannot parse Azure ID: parse "xxxxx": invalid URI for request
│ with azurerm_monitor_autoscale_setting.spring_apps_app_carrier_events,
The target_resource_id should not be in just number id form,
It has to be something like /subscriptions/xxxxxc/resourceGroups/<myrg>/providers/Microsoft.xxx/xx/sxx
In your case,
target_resource_id = module.spring_apps_app_carrier_events.app_identities[0].principal_id
gives the principal Id which is in “23434354544466” format which is not correct.
I tried below code with targetid being, resourceId : /subscriptions/xxx/resourceGroups/ <myrg>/providers/Microsoft.AppPlatform/spring/springcloudappkavya/apps/kaexamplspringcloudapp/deployments/kavyadeploy1
Code:
resource "azurerm_spring_cloud_service" "example" {
name = "springcloudappkavya"
location =data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
sku_name = "S0"
config_server_git_setting {
uri = "https://github.com/Azure-Samples/piggymetrics"
label = "config"
search_paths = ["dir1", "dir2"]
}
trace {
connection_string = azurerm_application_insights.example.connection_string
sample_rate = 10.0
}
tags = {
Env = "staging"
}
}
resource "azurerm_spring_cloud_app" "example" {
name = "kaexamplspringcloudapp"
resource_group_name = data.azurerm_resource_group.example.name
service_name = azurerm_spring_cloud_service.example.name
identity {
type = "SystemAssigned"
}
}
resource "azurerm_spring_cloud_java_deployment" "test" {
name = "kavyadeploy1"
spring_cloud_app_id = azurerm_spring_cloud_app.example.id
instance_count = 2
jvm_options = "-XX:+PrintGC"
quota {
cpu = "2"
memory = "4Gi"
}
runtime_version = "Java_11"
environment_variables = {
"Foo" : "Bar"
"Env" : "Staging"
}
}
resource "azurerm_monitor_autoscale_setting" "spring_apps_app_carrier_events" {
name = "default_auto_scale"
enabled = true
resource_group_name = data.azurerm_resource_group.example.name
location = data.azurerm_resource_group.example.location
target_resource_id = azurerm_spring_cloud_java_deployment.test.id
// target_resource_id = .spring_apps_app_carrier_events.app_identities[0].principal_id
// target_resource_id = "18xxxxxe2"
profile {
name = "metricRules"
capacity {
default = 1
minimum = 1
maximum = 2
}
rule {
metric_trigger {
dimensions {
name = "AppName"
operator = "Equals"
values = [azurerm_spring_cloud_app.example.name]
}
dimensions {
name = "Deployment"
operator = "Equals"
values = [azurerm_spring_cloud_java_deployment.test.name]
}
metric_name = "AppCpuUsage"
metric_namespace = "microsoft.appplatform/spring"
metric_resource_id = azurerm_spring_cloud_service.example.id
time_grain = "PT1M"
statistic = "Average"
time_window = "PT5M"
time_aggregation = "Average"
operator = "GreaterThan"
threshold = 75
}
scale_action {
direction = "Increase"
type = "ChangeCount"
value = 1
cooldown = "PT1M"
}
}
}
}
Could execute without errors.
Portal view of Autoscale settings for spring apps.
Reference : An Azure Spring Cloud Update: Managed Virtual Network and Autoscale are now generally available in Azure Spring Cloud

Terraform Alerts for Azure Functions

I am trying to research if it is possible to create alerts for azure functions via terraform.
My goal is to create a general rule that can be setup for on going functions that would alert us if an automated/timed function fails for x amount of times
I tried to reproduce the same in my environment to create the Alerts in Function app using Terraform:
Terraform code.
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "thejesh-rg" {
name = "Thejesh-RG-resources"
location = "West Europe"
}
resource "azurerm_storage_account" "thejeshstorage" {
name = "thejeshstorageaccount"
resource_group_name = azurerm_resource_group.thejesh-rg.name
location = azurerm_resource_group.thejesh-rg.location
account_tier = "Standard"
account_replication_type = "LRS"
}
resource "azurerm_service_plan" "thejeshsp" {
name = "thejeshsp-app-service-plan"
resource_group_name = azurerm_resource_group.thejesh-rg.name
location = azurerm_resource_group.thejesh-rg.location
os_type = "Linux"
sku_name = "P1v2"
}
resource "azurerm_linux_function_app" "thejesh" {
name = "thejesh-linux-function-app"
resource_group_name = azurerm_resource_group.thejesh-rg.name
location = azurerm_resource_group.thejesh-rg.location
storage_account_name = azurerm_storage_account.thejeshstorage.name
storage_account_access_key = azurerm_storage_account.thejeshstorage.primary_access_key
service_plan_id = azurerm_service_plan.thejeshsp.id
site_config {}
}
resource "azurerm_monitor_action_group" "actiongroup" {
name = "thejesh-actiongroup"
resource_group_name = azurerm_resource_group.thejesh-rg.name
short_name = "exampleact"
email_receiver{
email_address = "Email-ID"
name = "sendtoadmin"
}
}
resource "azurerm_monitor_metric_alert" "metrics" {
name = "theja-metricalert"
resource_group_name = azurerm_resource_group.thejesh-rg.name
scopes = [azurerm_linux_function_app.thejesh.id]
description = "Action will be triggered when Transactions count is greater than 1."
criteria {
metric_namespace = "Microsoft.Web/sites"
metric_name = "Requests"
aggregation = "Total"
operator = "GreaterThan"
threshold = "1"
}
action {
action_group_id = azurerm_monitor_action_group.actiongroup.id
}
}
Terraform Plan:
Terraform Apply
Once ran the code resources are created.
Alert notification.
Successfully received email.
Yes it's possible. See the documentation here.
Sample taken from the docs is creating a metric alert:
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_storage_account" "to_monitor" {
name = "examplestorageaccount"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "LRS"
}
resource "azurerm_monitor_action_group" "main" {
name = "example-actiongroup"
resource_group_name = azurerm_resource_group.example.name
short_name = "exampleact"
webhook_receiver {
name = "callmyapi"
service_uri = "http://example.com/alert"
}
}
resource "azurerm_monitor_metric_alert" "example" {
name = "example-metricalert"
resource_group_name = azurerm_resource_group.example.name
scopes = [azurerm_storage_account.to_monitor.id]
description = "Action will be triggered when Transactions count is greater than 50."
criteria {
metric_namespace = "Microsoft.Storage/storageAccounts"
metric_name = "Transactions"
aggregation = "Total"
operator = "GreaterThan"
threshold = 50
dimension {
name = "ApiName"
operator = "Include"
values = ["*"]
}
}
action {
action_group_id = azurerm_monitor_action_group.main.id
}
}

how to create generic cosmos db terraform module to add multiple geo_locations

I'm trying to create a module for azure cosmos db using terraform. In my example I wanted geo_location should be more flexible/customized. Which means my failover locations are not standard for all my applications. In one of the application my primary location is WEU but failover is EUS. In other application Primary is EUS but failover location is WEU, WUS2. and so on... So I wanted to use 1 cosmosdb module and the geo_location property should be more self service oriented where infra developers can specify any number of regions they require.
I see that in terraform we have to specify "geo_location" block for every region. This approach will defeat the purpose of having 1 module. Is there anyway can I make it more generic like I explained above?
Any suggestions are helpful.
thanks,
Santosh
If I understand your requirement correctly , You want to build a module for Cosmos DB where the operator will be asked to provide any number of values for geo location and the resource block will create the geo_location blocks accordingly.
In the above case you can create a variable of list type , which will ask the user to provide the values for the same and then use dynamic geo_location block so that it gets configured accordingly. I have tested with the below code :
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = "cosmos-dbtest"
location = "East US"
}
variable "geo_location" {
type = list
description = "value for Geo Locations"
}
resource "random_integer" "ri" {
min = 10000
max = 99999
}
resource "azurerm_cosmosdb_account" "db" {
name = "tfex-cosmos-db-${random_integer.ri.result}"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
offer_type = "Standard"
kind = "MongoDB"
enable_automatic_failover = true
capabilities {
name = "EnableAggregationPipeline"
}
capabilities {
name = "mongoEnableDocLevelTTL"
}
capabilities {
name = "MongoDBv3.4"
}
capabilities {
name = "EnableMongo"
}
consistency_policy {
consistency_level = "BoundedStaleness"
max_interval_in_seconds = 300
max_staleness_prefix = 100000
}
dynamic "geo_location" {
for_each = var.geo_location
content{
location = geo_location.value
failover_priority = geo_location.key
}
}
}
Output:
OR
If you want to keep the first geo_location same as the location for cosmos DB and then other failover locations , then you can use one static and one dynamic geo_location block like below:
resource "azurerm_cosmosdb_account" "db" {
name = "tfex-cosmos-db-${random_integer.ri.result}"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
offer_type = "Standard"
kind = "MongoDB"
enable_automatic_failover = true
capabilities {
name = "EnableAggregationPipeline"
}
capabilities {
name = "mongoEnableDocLevelTTL"
}
capabilities {
name = "MongoDBv3.4"
}
capabilities {
name = "EnableMongo"
}
consistency_policy {
consistency_level = "BoundedStaleness"
max_interval_in_seconds = 300
max_staleness_prefix = 100000
}
geo_location {
location = azurerm_resource_group.rg.location
failover_priority = 0
}
dynamic "geo_location" {
for_each = var.geo_location
content{
location = geo_location.value
failover_priority = "${geo_location.key + 1}"
}
}
}
Output:

How to create different metric type alerts for multiple resources of same resource type

I am working on to create the alerts in azure with Terraform scripts. I am trying to create different metric type alerts for different resources. (For example: functionapp01, functionapp02, logicapp01 and logicapp02 etc.)
This is the script:
terraform {
required_version = ">=0.12"
}
resource "azurerm_monitor_metric_alert" "metric_alert" {
name = var.metric_alert_name
resource_group_name = var.rg_name
scopes = [var.resource_id_01,var.resource_id_02]
description = var.metric_alert_description
tags = var.tags
frequency = var.frequency
severity = var.severity
window_size = var.window_size
enabled = var.is_enabled
criteria {
metric_namespace = var.metric_namespace
metric_name = var.metric_name
aggregation = var.aggregation
operator = var.operator
threshold = var.threshold
}
action {
action_group_id = var.action_group_id
}
}
Whenever I run the above script, then I am getting the below error:
Service returned an error. Status=400 Code="BadRequest" Message="Alerts are currently not supported with multi resource level for microsoft.web/sites
Reference Links:
azurerm_monitor_metric_alert
Metrics and Dimensions Supported
So, can anyone suggest me on this issue?
As the error show, the microsoft.web/sites resource type does not support Multi-resource alerts, refer to https://learn.microsoft.com/en-us/azure/azure-monitor/platform/alerts-metric-near-real-time#metrics-and-dimensions-supported
In this case, you have to create each monitor_metric_alert on each resource level.
For example, if you have created two functions, functionapp01, functionapp02. You can do it like this.
variable "function_apps" {
default = ["functionapp01","functionapp02"]
}
data "azurerm_function_app" "example" {
for_each = toset(var.function_apps)
name = each.value
resource_group_name = "funtions_rg"
}
resource "azurerm_monitor_metric_alert" "metric_alert" {
for_each = toset(var.function_apps)
name = "${each.value}-example-metricalert"
resource_group_name = var.rg_name
scopes = [data.azurerm_function_app.example[each.value].id]
description = var.metric_alert_description
tags = var.tags
frequency = var.frequency
severity = var.severity
window_size = var.window_size
enabled = var.is_enabled
criteria {
metric_namespace = var.metric_namespace
metric_name = var.metric_name
aggregation = var.aggregation
operator = var.operator
threshold = var.threshold
}
action {
action_group_id = var.action_group_id
}
}
Update
If you have function app resources is being created with Terraform, you can use them like this:
variable "function_apps" {
default = ["functionapp01","functionapp02"]
}
resource "azurerm_function_app" "example" {
for_each = toset(var.function_apps)
name = "${each.value}-example-funapp"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
app_service_plan_id = azurerm_app_service_plan.example.id
storage_account_name = azurerm_storage_account.example.name
storage_account_access_key = azurerm_storage_account.example.primary_access_key
app_settings = { }
version = "~3"
}
resource "azurerm_monitor_metric_alert" "test" {
for_each = toset(var.function_apps)
name = "${each.value}-example-metricalert"
resource_group_name = azurerm_resource_group.example.name
scopes = [azurerm_function_app.example[each.value].id]
description = var.metric_alert_description
severity = var.severity
window_size = var.window_size
enabled = var.is_enabled
criteria {
metric_namespace = var.metric_namespace
metric_name = var.metric_name
aggregation = var.aggregation
operator = var.operator
threshold = var.threshold
}
action {
action_group_id = var.action_group_id
}
}

issue to setup alert onAazure Postgresql using Terraform

I have created postgresql with custome alert for cpu percentage using Terraform azure and its showing error metric name is not found
Please check the following code.
provider "azurerm" {
features {}
subscription_id = "***************"//add subscription ID
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_postgresql_server" "example" {
name = "example-psqlserver"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
administrator_login = "psqladminun"
administrator_login_password = "H#Sh1CoR3!"
sku_name = "GP_Gen5_4"
version = "9.6"
storage_mb = 640000
backup_retention_days = 7
geo_redundant_backup_enabled = true
auto_grow_enabled = true
public_network_access_enabled = false
ssl_enforcement_enabled = true
ssl_minimal_tls_version_enforced = "TLS1_2"
}
resource "azurerm_monitor_action_group" "actiongrp" {
name = "Postgresql-AlertsActions1"
resource_group_name = azurerm_resource_group.example.name
short_name = "Postgresql1"
email_receiver {
name = "sendtoadmin"
email_address = "testing#gmail.com"
}
}
////This alert is Trigger once the CPU usage is goes more than 70
resource "azurerm_monitor_metric_alert" "alert0" {
name = "testing"
resource_group_name = azurerm_resource_group.example.name
scopes = [azurerm_postgresql_server.example.id]
description = "Action will be triggered when CPU Utilization count is greater than 70."
criteria {
metric_namespace = "Microsoft.DBforPostgreSQL/servers"#"Microsoft.DBforPostgreSQL/servers"
metric_name = "CPU percent"
aggregation = "Average"
operator = "GreaterThan"
threshold = 70
}
action {
action_group_id = azurerm_monitor_action_group.actiongrp.id
}
}
Error Screenshot
Below Microsoft DOC link is refer for alert specification-
https://learn.microsoft.com/en-us/azure/azure-monitor/platform/metrics-supported
You just need to change the metric_name value in the criteria block from CPU percent into cpu_percent. It should be the name of the Metric, not the Metric Display Name.

Resources