【Azure APIM】使用 Terraform 为现有 APIM 配置自动缩放

简介: 本文详解如何使用Terraform为Azure API Management(APIM)配置自动缩放。因官方azurerm_api_management资源不支持auto scale参数,需借助azurerm_monitor_autoscale_setting资源实现,并适配中国区环境(设置environment="china")。文中提供完整模板、部署步骤及常见错误解决方案。(240字)

问题描述

API Management服务的自动缩放通过门户配置非常的便捷。但是如果使用Terraform呢?

在官网关于APIM模板(azurerm_api_management)的介绍中,并没有发现可以设置auto scale的参数。那么,应该如何配置呢?

 

问题解答

由于Azure API Management(APIM)的自动缩放功能是通过Azure Monitor来实现的,作为一个单独的自动缩放设置资源来实现的。

Teffaform是基于azurerm_monitor_autoscale_setting来实现Azure APIM自动缩放功能的。

模板结构如下(完整的模板见附件):

在准备好模板之后,需要先登录到中国区Azure云( 先设置云环境 az cloud set --name AzureChinaCloud 后,在使用 az login 登录)。

随后,初始化 Terraform 文件并生成执行计划。

#初始化
terraform init
#验证
terraform validate
#生成执行计划文件
terraform plan -out=apim-autoscale.tfplan
#开始执行修改
terraform apply apim-autoscale.tfplan

初始化会下载 Provider,并生成依赖锁文件。校验通过只表示配置结构有效,不代表云端权限、指标和配额已验证。部署前,先在门户检查目标 APIM 是否已有自动缩放设置。


注意:如果在生成Plan文件的时候遇见如下错误,这是因为在Terraform模板文件中没有执行云环境有关。在Provider "azurerm"内容中配置 environment = "china" 就可以解决此问题。

Planning failed. Terraform encountered an error while generating this plan.
│ Error: building account: could not acquire access token to parse claims: running Azure CLI: 
exit status 1: ERROR: V2Error: invalid_resource AADSTS500011: 
The resource principal named https://graph.microsoft.com was not found in the tenant named ********-****-****-****-************. 
This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant.
 You might have sent your authentication request to the wrong tenant. 
Trace ID:*********** Timestamp: 2026-10-28 06:43:12Z.
Status: Response_Status.Status_IncorrectConfiguration, Error code: 3399614475, Tag: 508634112
│ Run the command below to authenticate interactively; additional arguments may be added as needed:
│ az logout
│ az login --tenant "****************" --scope "https://graph.microsoft.com/.default"
│   with provider["registry.terraform.io/hashicorp/azurerm"],
│   on autoscale.tf line 12, in provider "azurerm":
│   12: provider "azurerm" {


执行完成后,可APIM门户中查看是否生效。

 

附录:完整的Teffaform模板


terraform {
  required_version = ">= 1.5.0"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 5.11"
    }
  }
}
provider "azurerm" {
  environment = "china"
  features {}
  subscription_id = "**********  your subscription id"
  # Authenticate externally; do not store credentials in this file.
}
# Read only: this configuration does not create, import, or manage the APIM itself.
# Existing ID: /subscriptions/**********/resourceGroups/lb-*******-rg/providers/Microsoft.ApiManagement/service/lb**********02
data "azurerm_api_management" "apim" {
  name                = "your apim name **********
  resource_group_name = "your reousrce group **********
}
variable "apim_scale_step" {
  type        = number
  description = "Units per scaling action. If APIM explicitly selects availability zones, set this to the number of selected zones; otherwise leave 1."
  default     = 1
  validation {
    condition     = var.apim_scale_step >= 1 && var.apim_scale_step <= 3 && floor(var.apim_scale_step) == var.apim_scale_step
    error_message = "apim_scale_step must be an integer from 1 to 3 matching the explicit zone count, or 1 for automatic/no explicit zones."
  }
}
locals {
  apim_tier = split("_", data.azurerm_api_management.apim.sku_name)[0]
  is_v2     = endswith(lower(local.apim_tier), "v2")
  # Capacity is not supported on v2. Scale out on either CPU or memory;
  # Azure Monitor requires all scale-in rules to be satisfied before scaling in.
  scale_metrics = local.is_v2 ? ["CpuPercent_Gateway", "MemoryPercent_Gateway"] : ["Capacity"]
  # This provider's APIM data source does not export zones. For explicitly
  # selected zones, set apim_scale_step to the zone count before applying.
  scale_step = var.apim_scale_step
  # Preserve the requested cap of 5 where supported; classic Basic/Standard
  # have lower limits. Round down to a valid explicit-zone multiple.
  requested_maximum = min(5, lookup({ Basic = 2, Standard = 4 }, local.apim_tier, 5))
  maximum_units     = floor(local.requested_maximum / local.scale_step) * local.scale_step
}
resource "azurerm_monitor_autoscale_setting" "apim" {
  name                = "${data.azurerm_api_management.apim.name}-autoscale"
  resource_group_name = data.azurerm_api_management.apim.resource_group_name
  location            = data.azurerm_api_management.apim.location
  target_resource_id  = data.azurerm_api_management.apim.id
  enabled             = true
  profile {
    name = "default"
    capacity {
      # Default is a fallback for missing metrics, not the initial APIM count.
      default = local.scale_step
      minimum = local.scale_step
      maximum = local.maximum_units
    }
    # Scale out: 30-minute average > 70%; wait 60 minutes between actions.
    dynamic "rule" {
      for_each = local.scale_metrics
      iterator = metric
      content {
        metric_trigger {
          metric_name              = metric.value
          metric_namespace         = "Microsoft.ApiManagement/service"
          metric_resource_id       = data.azurerm_api_management.apim.id
          divide_by_instance_count = false
          time_grain               = "PT1M"
          statistic                = "Average"
          time_window              = "PT30M"
          time_aggregation         = "Average"
          operator                 = "GreaterThan"
          threshold                = 70
          # Only the primary region can be autoscaled. v2 metrics have no dimensions.
          dynamic "dimensions" {
            for_each = local.is_v2 ? [] : [data.azurerm_api_management.apim.location]
            content {
              name     = "Location"
              operator = "Equals"
              values   = [dimensions.value]
            }
          }
        }
        scale_action {
          direction = "Increase"
          type      = "ChangeCount"
          value     = tostring(local.scale_step)
          cooldown  = "PT60M"
        }
      }
    }
    # Scale in: all 30-minute averages < 35%; wait 90 minutes between actions.
    dynamic "rule" {
      for_each = local.scale_metrics
      iterator = metric
      content {
        metric_trigger {
          metric_name              = metric.value
          metric_namespace         = "Microsoft.ApiManagement/service"
          metric_resource_id       = data.azurerm_api_management.apim.id
          divide_by_instance_count = false
          time_grain               = "PT1M"
          statistic                = "Average"
          time_window              = "PT30M"
          time_aggregation         = "Average"
          operator                 = "LessThan"
          threshold                = 35
          dynamic "dimensions" {
            for_each = local.is_v2 ? [] : [data.azurerm_api_management.apim.location]
            content {
              name     = "Location"
              operator = "Equals"
              values   = [dimensions.value]
            }
          }
        }
        scale_action {
          direction = "Decrease"
          type      = "ChangeCount"
          value     = tostring(local.scale_step)
          cooldown  = "PT90M"
        }
      }
    }
  }
  lifecycle {
    precondition {
      condition     = contains(["Basic", "Standard", "Premium", "BasicV2", "StandardV2", "PremiumV2"], local.apim_tier)
      error_message = "Autoscale requires a supported dedicated APIM tier; Developer and Consumption are not supported by this configuration."
    }
    precondition {
      condition     = local.maximum_units >= local.scale_step
      error_message = "The maximum unit count must accommodate the configured availability zones."
    }
  }
}
# If an autoscale setting already exists for this APIM, import that setting
# into azurerm_monitor_autoscale_setting.apim instead of creating a second one.
# Protect Terraform state: data sources can include sensitive APIM properties.

 

参考资料

APIM 自动缩放 : https://learn.microsoft.com/azure/api-management/api-management-howto-autoscale

Terraform 自动缩放资源 : https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/monitor_autoscale_setting

 


当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

相关文章
|
1月前
|
Windows
【Azure Service Fabric 】节点扩展状态为 Not Ready 的恢复办法
Azure Service Fabric Windows节点卡在“Node configuration is in progress”状态,实为扩展未就绪(Not Ready),非正常进行中。本文详解通过停止服务、重命名运行时目录、重启安装服务及虚拟机,触发自动修复完成节点恢复的实操方案。
133 2
|
19天前
|
安全
【App Service】为应用服务添加Key Vault证书时遇见的RBAC问题之两个困扰人的坑
本文详解Azure App Service通过RBAC方式从Key Vault导入HTTPS证书的三大权限坑:门户无法加载证书列表、Add时仍报无权访问。关键在于开启Key Vault诊断日志定位Forbidden错误,并为App Service托管标识、当前用户授予“Key Vault Certificate User”,为Microsoft.Azure.WebSites授予“Key Vault Secrets User”权限。
|
1月前
|
BI
同一张业务表,还要反复核对?SpreadJS V19.2 & GcExcel V9.2 新版本发布直播
9月23日14:00直播|详解SpreadJS新版本如何轻松解决业务系统三大痛点:多人协同不冲突、业务数据直出报表、中文Excel操作少踩坑。GcExcel V9.2同步升级,支持异常公式容错与多格式导出。已在用或正选型的企业必看!
|
1月前
|
人工智能
GEO虚假信源正在泛滥,我们公开了第一批疑似风险渠道
GEO行业高速增长,但“信源造假”频发:山寨域名、品牌仿冒、文档伪装媒体等乱象丛生。GEO信源网上线开源风险核验体系(GitHub:315fang/fake-geo-channels),已识别306台风险主机、951条可疑目录,全部标注“疑似风险”,支持申诉与复核,推动信源透明化、可验证、可追溯。(239字)
268 6
|
1月前
|
人工智能 API 开发工具
阿里云百炼计费选择TokenPlan、CodingPlan还是按量付费?三种计费方式详解
阿里云百炼是AI大模型服务平台,免费提供千万级Tokens。支持三种计费方式:按量付费(单价×Token数)、TokenPlan(按Credits订阅)、CodingPlan(按调用次数计费)。开通后可获取API Key,接入Cursor、Qwen Code、Claude Code等主流AI工具。在阿里云百炼官网:https://t.aliyun.com/U/fPVHqY 免费领取千万Tokens
|
1月前
|
缓存 NoSQL Java
私域流量变现:母婴社群如何通过API选品实现月销百万?
本文聚焦母婴私域变现痛点,提出基于API选品的数据驱动方案:打通电商数据源、规则引擎筛选、企微自动推送、订单效果回流,实现从“人工推荐”到“自动化变现引擎”的升级,助力社群稳定月销百万。
|
6月前
|
NoSQL 网络协议 Cloud Native
【Azure Redis】云原生环境下的 Redis 超时之谜:为什么 15 分钟后应用才恢复?
云原生中Redis短暂不可用后应用持续超时15分钟?问题不在Redis,而在Linux TCP默认重传机制(tcp_retries2=15)与长连接模型的错位。需三管齐下:调低内核重传次数、客户端显式配置超时与自动重连、应用层引入断路器与弹性重试。
383 20
|
6月前
|
网络协议 虚拟化 Docker
【Azure Developer】.NET Aspire 启动报错:listen tcp bind: An attempt was made to access a socket in a way forbidden by its access permissions
.NET Aspire在Windows启动时因Hyper-V端口保留机制,导致DCP代理无法绑定53209等端口(报错“访问被拒绝”)。虽端口未被占用,但已被系统保留。推荐方案:修改launchSettings.json,将服务端口改为7xxx等安全范围;或临时重启winnat服务、永久排除指定端口。
815 21
|
6月前
|
人工智能 监控 网络协议
【App Service】常规排查 App Service 启动 Application Insights 无数据的步骤 (.NET版本)
本文详解Application Insights在Azure App Service中无日志数据的三大原因及排查方法:1)网络连通性(验证到AI端点的443端口访问);2)w3wp.exe进程是否成功加载AI模块;3)DLL冲突(检查并移除重复的Microsoft.ApplicationInsights等组件)。
293 10
|
6月前
|
前端开发 应用服务中间件 Linux
【Azure App Service】PHP页面上传文件413错误的解决方案
在使用 Azure App Service(Linux + PHP) 部署 Web 应用时,如果上传文件大于1MB,就会遇到 HTTP 413(Request Entity Too Large) 错误。 # 问题解答 ### 一、HTTP 413 错误的本质含义 413 Request Entity Too Large 是标准 HTTP 状态码,表示: > 客户端提交的请求体(Request Body)大小超过了服务器当前允许的最大限制。 在 Azure App Service(Linux)环境中,这个错误并不一定来自前端网关(Frontend),而更常见的来源是 App...
1703 13