使用Terraform将Azure Blob存储的JSON文件导入至Azure Cosmos MongoDB集合
Terraform实现Azure Blob JSON文件批量导入Cosmos MongoDB集合
实现逻辑
通过Terraform的null_resource结合Azure CLI命令,批量遍历Blob存储中的JSON文件,将每个文件导入到同名的Cosmos MongoDB集合中。核心是利用for_each实现文件与集合的一一对应,同时通过Azure CLI完成数据导入操作。
示例代码
# 配置Azure Provider版本约束 terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "~> 3.0" } null = { source = "hashicorp/null" version = "~> 3.2" } } } # 初始化Azure Provider provider "azurerm" { features {} } # 定义需替换的资源变量 variable "cosmosdb_account" { type = string description = "目标Cosmos DB账户名称" } variable "resource_group" { type = string description = "资源组名称" } variable "mongodb_db" { type = string description = "Cosmos DB中的MongoDB数据库名称" } variable "storage_account" { type = string description = "存储JSON文件的Azure存储账户名称" } variable "blob_container" { type = string description = "存储JSON文件的Blob容器名称" } variable "blob_folder" { type = string description = "Blob容器内存储JSON文件的文件夹路径(无需结尾斜杠)" } # 生成Blob文件的只读SAS URL(用于访问私有Blob) data "azurerm_storage_account_sas" "blob_read" { connection_string = azurerm_storage_account.target_storage.primary_connection_string https_only = true resource_types { container = true object = true } services { blob = true } start = timestamp() expiry = timeadd(timestamp(), "24h") permissions { read = true } } # 假设已将Blob文件夹下的JSON文件同步到本地`./json_files`目录,遍历所有JSON文件 locals { json_file_list = fileset("${path.module}/json_files", "*.json") # 提取文件名(去掉.json后缀)作为集合名称 file_to_collection = { for file in local.json_file_list : replace(file, ".json", "") => file } } # 批量执行导入操作 resource "null_resource" "batch_import" { for_each = local.file_to_collection provisioner "local-exec" { command = <<EOT az cosmosdb mongodb collection import \ --account-name ${var.cosmosdb_account} \ --resource-group ${var.resource_group} \ --database-name ${var.mongodb_db} \ --collection-name ${each.key} \ --file "https://${var.storage_account}.blob.core.windows.net/${var.blob_container}/${var.blob_folder}/${each.value}?${data.azurerm_storage_account_sas.blob_read.sas}" \ --json-format multi EOT } }
关键注意事项
- Blob文件同步:如果不想使用SAS URL,可提前运行
az storage blob download-batch --destination ./json_files --source ${var.blob_container} --pattern ${var.blob_folder}/*.json将文件同步到本地,此时--file参数改为本地文件路径(如./json_files/${each.value}) - JSON格式适配:
--json-format参数根据你的文件结构选择:single对应单个JSON对象文件,multi对应每行一个JSON对象的文件 - 权限配置:执行Terraform的账号需要拥有:
- Cosmos DB的
MongoDB Data Contributor角色权限 - 存储账户的
Storage Blob Data Reader角色权限
- Cosmos DB的
- 变量替换:所有变量需替换为你实际的Azure资源名称和路径
内容的提问来源于stack exchange,提问作者Mohan Kumar G
相关产品推荐
相关产品推荐

