auto scale azure spring app URI with terraform - 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

Related

Terraform Dynamic block for Application Gateway

I have the following list of objects defined as a local:
agw_configs = [
{
env = "dev"
function = "events"
backend_pool_fqdn = "dev.servicebus.windows.net"
cookie_based_affinity = "Enabled"
https_listener_hostname = "ingestiondev.co.uk"
},
{
env = "test"
function = "events"
backend_pool_fqdn = "test.servicebus.windows.net"
cookie_based_affinity = "Enabled"
https_listener_hostname = "ingestiontest.co.uk"
}
]
I now want to use multiple dynamic blocks within an Azure application gateway resource to create various settings for each environment. However I cannot figure out how to do this and keep getting undeclared resource errors. Here is my current config:
resource "azurerm_application_gateway" "application_gateway" {
name = local.application_gateway_name
resource_group_name = var.resource_group_name
location = var.location
sku {
name = var.sku.size
tier = var.sku.tier
capacity = var.sku.capacity
}
...
dynamic "backend_address_pool" {
for_each = local.agw_configs
content {
name = "${var.region}-${agw_configs.value.env}-${agw_configs.value.function}-beap"
fqdns = [agw_configs.value.backend_pool_fqdn]
}
}
Feels like i am almost there but not sure where I am going wrong
See an example that it works:
1/ Define the variable - with the
variable "backend_pools" {
type = map(string({
fqdn = string
ip_addresses = string
}))
#Define default value
default = {
"Pool1" = {
fqdns = "fqdns1"
ip_addresses = "10.0.0.0"
}
"pool2" = {
fqdns = "fqdns1"
ip_addresses = "10.10.0.0"
}
Then you can use the var from dynamic block into your azurerm_application_gateway block:
dynamic "backend_address_pool" {
for_each = var.backend_pools
content {
fqdns = backend_address_pool.value.fqdn
ip_addresses = backend_address_pool.value.ip_addresses
}
}

How to create alert rule in terraform for SQL DB

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

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
}
}

Deploying Service Fabric with Virtual Machine Scale Sets

I've managed to deploy my Service Fabric but struggling for it to communicate with the Virtual Machine Scale Sets. All the nodes have deployed but they're not communicating with Service Fabric.
I've tried adding more parameters to my resources but unfortunately I'm getting a very lame error message which doesn't make sense.
resource "azurerm_service_fabric_cluster" "brcgs-ngd-dev" {
name = "BRCGS-NGD-${var.environment}-SF"
resource_group_name = var.resource_group_name
location = var.location
reliability_level = "Bronze"
upgrade_mode = "Automatic"
vm_image = "Windows"
management_endpoint = "https://example.com/Explorer"
node_type {
name = "sfNodes"
instance_count = 3
is_primary = true
client_endpoint_port = "19000"
http_endpoint_port = "19080"
}
fabric_settings {
name = "Security"
parameters = {
"ClusterProtectionLevel" = "EncryptAndSign"
}
}
certificate {
thumbprint = "example"
thumbprint_secondary = "example"
x509_store_name = "my"
}
}
resource "azurerm_virtual_machine_scale_set" "sf-nodes" {
name = "sfNodes"
location = var.location
resource_group_name = var.resource_group_name
upgrade_policy_mode = "automatic"
sku {
name = "Standard_D1_V2"
tier = "Standard"
capacity = 3
}
storage_profile_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServerSemiAnnual"
sku = "Datacenter-Core-1803-with-Containers-smalldisk"
version = "latest"
}
storage_profile_os_disk {
os_type = "Windows"
caching = "ReadOnly"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}
os_profile {
computer_name_prefix = "sfNodes"
admin_username = "brcgsdev"
admin_password = var.adminpassword
}
os_profile_secrets = [
{
source_vault_id = "/subscriptions/exampleid/resourceGroups/rg-ngd-mig-inf-01/providers/Microsoft.KeyVault/vaults/kv-ngd-mig-infra"
vault_certificates = [
{
certificate_url = "https://example/certificates/cert/c5326f869a624079a0f1f48afe525331"
certificate_store = "My"
}
]
}
]
network_profile {
name = "NIC-brcgs-ngd-${var.environment}-sf-0"
primary = "true"
ip_configuration {
primary = "true"
name = "NIC-brcgs-ngd-${var.environment}-sf-0"
subnet_id = var.subnet_id
load_balancer_backend_address_pool_ids = [var.backendlb]
}
}
extension { # This extension connects vms to the cluster.
name = "ServiceFabricNodeVMscalesets"
publisher = "Microsoft.Azure.ServiceFabric"
type = "ServiceFabricNode"
type_handler_version = "1.0"
settings = "{ \"certificate\": { \"thumbprint\": \"example\", \"x509StoreName\": \"My\" } , \"clusterEndpoint\": \"example.uksouth.cloudapp.azure.com:19000\", \"nodeTypeRef\": \"sfNodes\", \"dataPath\": \"D:\\\\SvcFab\",\"durabilityLevel\": \"Bronze\",\"nicPrefixOverride\": \"******\"}"
}
}
The error message I get is
Error: Unsupported argument
on servicefabric\main.tf line 57, in resource "azurerm_virtual_machine_scale_set" "sf-nodes":
57: os_profile_secrets = [
An argument named "os_profile_secrets" is not expected here. Did you mean to
define a block of type "os_profile_secrets"?
As you can see the error message is not very helpful at all.
Can anyone help me on this?
Thanks
Terraform Template has a bit similar syntax with ARM Template. For the error message, you could define the os_profile_secrets as a block via removing "=". It looks like this:
os_profile_secrets {
source_vault_id = "/subscriptions/exampleid/resourceGroups/rg-ngd-mig-inf-01/providers/Microsoft.KeyVault/vaults/kv-ngd-mig-infra"
vault_certificates {
certificate_url = "https://example/certificates/cert/c5326f869a624079a0f1f48afe525331"
certificate_store = "My"
}
}
To deploy Service Fabric and instances with Terraform, here is an example for deploying Linux nodes for your reference.

How to use terraform template to add an Azure VM into a recovery service vault?

I'm developing a terraform template to automatically enroll a new built Azure VM to Azure recovery service vault. All the resources I can found in Azurerm provider are
azurerm_recovery_services_protection_policy_vm
azurerm_recovery_services_protected_vm
azurerm_recovery_services_vault
Seems none of them can enroll a VM to recovery service vault. Does Terraform have this feature?
You can see the azurerm_recovery_services_protected_vm in Terraform, and the argument source_vm_id shows:
Specifies the ID of the VM to backup
It can refer to the VM which you want to back up in the recovery service vault. Create the policy with azurerm_recovery_services_protection_policy_vm and the recovery service vault with azurerm_recovery_services_vault.
Update
You can back up the VM with Recovery vault with azurerm_recovery_services_protected_vm through Terraform. The code like this:
data "azurerm_virtual_machine" "azurevm" {
name = "vm_name"
resource_group_name = "group_name"
}
resource "azurerm_resource_group" "rg" {
name = "recovery_group_name"
location = "eastus"
}
resource "azurerm_recovery_services_vault" "vault" {
name = "azurerecoveryvaulti1"
location = "${azurerm_resource_group.rg.location}"
resource_group_name = "${azurerm_resource_group.rg.name}"
sku = "Standard"
}
resource "azurerm_recovery_services_protection_policy_vm" "test" {
name = "azurerecoveryvaultpolicy1"
resource_group_name = "${azurerm_resource_group.rg.name}"
recovery_vault_name = "${azurerm_recovery_services_vault.vault.name}"
backup = {
frequency = "Daily"
time = "23:00"
}
retention_daily = {
count = 1
}
}
resource "azurerm_recovery_services_protected_vm" "example" {
resource_group_name = "${azurerm_resource_group.rg.name}"
recovery_vault_name = "${azurerm_recovery_services_vault.vault.name}"
source_vm_id = "${data.azurerm_virtual_machine.azurevm.id}"
backup_policy_id = "${azurerm_recovery_services_protection_policy_vm.test.id}"
}
For the test, I create the new Recovery Vault. You can use the existing with data azurerm_recovery_services_vault. Create a new policy then create the back up the vm with azurerm_recovery_services_protected_vm like above.
The resource type azurerm_recovery_services_protected_vm is no more supported hashicorp/azurerm provider
You can use azurerm_backup_protected_vm instead of azurerm_recovery_services_protected_vm,
resource "azurerm_backup_policy_vm" "vm_backup_policy" {
count = var.vm_backup_policy_name != "" ? 1 : 0
name = var.vm_backup_policy_name
resource_group_name = var.resource_group_name
recovery_vault_name = azurerm_recovery_services_vault.vault.name
timezone = var.vm_backup_policy_timezone
backup {
frequency = var.vm_backup_policy_frequency
time = var.vm_backup_policy_time
}
retention_daily {
count = var.vm_backup_daily_policy_retention
}
dynamic "retention_weekly" {
for_each = var.vm_backup_weekly != {} ? [var.vm_backup_weekly] : []
content {
count = lookup(retention_weekly.value, "count")
weekdays = lookup(retention_weekly.value, "weekdays")
}
}
dynamic "retention_monthly" {
for_each = var.vm_backup_monthly != {} ? [var.vm_backup_monthly] : []
content {
count = lookup(retention_monthly.value, "count")
weekdays = lookup(retention_monthly.value, "weekdays")
weeks = lookup(retention_monthly.value, "weeks")
}
}
dynamic "retention_yearly" {
for_each = var.vm_backup_yearly != {} ? [var.vm_backup_yearly] : []
content {
count = lookup(retention_yearly.value, "count")
weekdays = lookup(retention_yearly.value, "weekdays")
weeks = lookup(retention_yearly.value, "weeks")
months = lookup(retention_yearly.value, "months")
}
}
}
resource "azurerm_backup_protected_vm" "vm" {
resource_group_name = var.resource_group_name
recovery_vault_name = var.recovery_vault_custom_name
source_vm_id = var.source_vm_id
backup_policy_id = azurerm_backup_policy_vm.vm_backup_policy.id
}

Resources