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

如何通过Terraform为Azure Blob Storage动态设置Content-Type?

解决方案

可以通过Terraform的本地变量定义MIME类型映射,结合字符串处理函数动态提取文件扩展名并匹配对应的Content-Type。以下是修改后的完整代码:

locals {
  # 定义文件扩展名与Content-Type的映射,可根据需要扩展
  mime_types = {
    "json" = "application/json"
    "html" = "text/html"
    "pdf"  = "application/pdf"
    "png"  = "image/png"
    "jpg"  = "image/jpeg"
    "jpeg" = "image/jpeg"
    "css"  = "text/css"
    "js"   = "application/javascript"
    "svg"  = "image/svg+xml"
  }
}

resource "azurerm_storage_blob" "Example" {
  for_each                = fileset("${path.root}/assets/", "**/*")
  name                    = each.key
  storage_account_name    = azurerm_storage_account.example.name
  storage_container_name  = azurerm_storage_container.example.name
  type                    = "Block"
  source                  = "${path.root}/assets/${each.key}"
  content_md5             = filemd5("${path.root}/assets/${each.key}")
  # 动态匹配Content-Type,默认回退为application/octet-stream
  content_type            = lookup(
    local.mime_types,
    lower(regex("\\.(\\w+)$", each.key)[0]),
    "application/octet-stream"
  )
}

代码说明:

  • local.mime_types:维护一份扩展名到标准MIME类型的映射表,你可以根据实际上传的文件类型补充更多条目。
  • lower():统一转换扩展名的大小写,避免因.PNG、.Html这类大小写不一致的扩展名导致匹配失败。
  • regex("\.(\w+)$", each.key)[0]:通过正则表达式提取文件名最后一个点之后的扩展名部分,能正确处理类似file.v2.pdf这类包含多个点的文件名。
  • lookup():在映射表中查找对应的Content-Type,如果扩展名不在映射表中,就使用默认值application/octet-stream。

如果你的文件名存在没有扩展名的情况,正则表达式会报错,这时可以改用try函数做容错处理:

content_type = lookup(
  local.mime_types,
  lower(try(regex("\\.(\\w+)$", each.key)[0], "")),
  "application/octet-stream"
)

这样即使文件没有扩展名,也会默认使用application/octet-stream,避免Terraform执行报错。

内容的提问来源于stack exchange,提问作者The Grey Wolf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:25:42