You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform dynamic块for_each实现多存储实例CORS规则配置

Terraform 存储账户动态CORS规则配置方案

首先修正你现有代码里的两处基础问题:

  1. 变量定义语法错误:cors_rules中instance2的origin第一个值存在引号笔误,原写法https://instance2.com""缺少开头双引号、多了一个结尾双引号,不符合HCL语法规范,需要修正为标准字符串格式。
  2. 资源块结构错误:原代码中cors_rule的content块写到了dynamic块外部,不符合Terraform dynamic块的语法要求,需要嵌套在dynamic块内部。

修正后的完整变量定义

instances = ["instance1", "instance2"]

cors_rules = {
  instance1 = {
    origin = ["https://instance.com", "http://localhost:4200"],
  },
  instance2 = {
    origin = ["https://instance2.com", "http://localhost:4200"],
  }
}

修正后的资源定义(含核心dynamic块逻辑)

resource "azurerm_storage_account" "storage-account" {
  count                    = length(var.instances)
  name                     = "${var.storageAccount.name}${var.instances[count.index]}"
  location                 = var.location
  resource_group_name      = var.resource_name
  account_tier             = "Standard"
  account_replication_type = "LRS"

  blob_properties {
    dynamic "cors_rule" {
      # 核心逻辑:取当前count对应实例的CORS配置,包装为单元素列表传给for_each
      for_each = [var.cors_rules[var.instances[count.index]]]
      content {
        allowed_origins    = cors_rule.value.origin
        allowed_methods    = ["DELETE", "GET", "POST", "OPTIONS", "PUT", "PATCH"]
        allowed_headers    = ["*"]
        exposed_headers    = ["*"]
        max_age_in_seconds = 200
      }
    }
  }
}

逻辑说明

  • 用count创建多实例时,var.instances[count.index]可以拿到当前循环对应的实例名称
  • 用实例名称作为key,直接从var.cors_rules映射中取到该实例对应的CORS origin配置
  • 将单条配置包装为列表传入for_each,会为每个存储账户生成恰好1条匹配的CORS规则,完全匹配实例对应配置的需求
  • 如果后续需要支持某个实例不配置CORS规则,只需要把对应实例从cors_rules映射中移除,同时把for_each改成try([var.cors_rules[var.instances[count.index]]], [])即可自动跳过配置,不需要修改资源主体代码

内容的提问来源于stack exchange,提问作者iluv_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 13:48:13