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

如何用Terraform在Azure文件共享中动态创建目录并上传文件

Terraform动态迭代实现Azure File Share目录创建与文件上传

核心思路

利用Terraform的for_each元参数结合fileset函数,批量遍历本地文件,动态生成对应的存储目录和文件资源。

完整示例代码

# 配置Azure Provider
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

provider "azurerm" {
  features {}
}

# 引用已存在的存储账户和文件共享(若未创建,可自行添加对应资源块)
data "azurerm_storage_account" "example" {
  name                = "your-storage-account-name"
  resource_group_name = "your-resource-group-name"
}

data "azurerm_storage_share" "example" {
  name                 = "azurefileshare"
  storage_account_name = data.azurerm_storage_account.example.name
}

# 批量获取/workload目录下的所有json文件
locals {
  workload_files = fileset("/workload", "*.json")
}

# 动态创建对应目录
resource "azurerm_storage_share_directory" "workload_dirs" {
  for_each             = toset(local.workload_files)
  name                 = split(".", each.value)[0] # 提取文件名(去掉.json后缀)作为目录名
  storage_share_name   = data.azurerm_storage_share.example.name
  storage_account_name = data.azurerm_storage_account.example.name
}

# 动态上传文件到对应目录
resource "azurerm_storage_share_file" "workload_files" {
  for_each             = toset(local.workload_files)
  name                 = each.value
  storage_share_name   = data.azurerm_storage_share.example.name
  storage_account_name = data.azurerm_storage_account.example.name
  directory_path       = split(".", each.value)[0] # 关联对应创建的目录
  source               = "/workload/${each.value}"
}

关键技巧说明

  • fileset函数:批量获取指定目录下符合匹配规则的文件列表,这里fileset("/workload", "*.json")会返回["test1.json", "test2.json", ...]格式的集合。
  • for_each元参数:基于文件集合动态创建资源,每个文件对应一个目录和一个文件资源,避免count参数可能出现的索引偏移问题。
  • 文件名提取:通过split(".", each.value)[0]将文件名按.分割,取第一个元素作为目录名(如test1.json提取为test1)。

注意事项

  • 确保Terraform运行环境有权限访问本地/workload目录,同时拥有Azure存储账户的读写权限。
  • 若存储账户或文件共享尚未创建,可添加azurerm_storage_account和azurerm_storage_share资源块完成前置创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:06:03