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

Terraform Azurerm:配置Block Blob仅在不存在时创建

实现Terraform仅在Blob不存在时创建且不覆盖现有内容

要实现仅在Blob不存在时创建,且后续不覆盖手动修改的内容,你可以通过数据源检查Blob状态+资源创建条件控制+生命周期忽略变化的组合来实现,无需依赖外部脚本。

修改后的完整代码

locals {
  storage_account_name_teast = format("%s%s", local.main_pw_prefix_short, "teast")
}

resource "azurerm_storage_account" "teaststorage" {
  name                            = local.storage_account_name_teast
  resource_group_name             = azurerm_resource_group.main.name
  location                        = var.location
  account_tier                    = var.account_tier
  account_replication_type        = var.account_replication_type
  allow_nested_items_to_be_public = false
  min_tls_version                 = "TLS1_2"

  network_rules {
    default_action = "Deny"
    bypass = [
      "AzureServices"
    ]
    virtual_network_subnet_ids = []
    ip_rules                   = local.ip_rules
  }
  tags = var.tags
}

resource "azurerm_storage_container" "teastconfig" {
  name                  = "config"
  storage_account_name  = azurerm_storage_account.teaststorage.name
  container_access_type = "private"
}

# 检查目标Blob是否已存在
data "azurerm_storage_blob" "teastfeaturetoggle" {
  name                   = "featureToggles.json"
  storage_account_name   = azurerm_storage_account.teaststorage.name
  storage_container_name = azurerm_storage_container.teastconfig.name

  depends_on = [azurerm_storage_container.teastconfig]
}

resource "azurerm_storage_blob" "teastfeaturetoggle" {
  # 仅当Blob不存在时才创建(数据源id为空表示不存在)
  count = data.azurerm_storage_blob.teastfeaturetoggle.id == "" ? 1 : 0

  name                   = "featureToggles.json"
  storage_account_name   = azurerm_storage_account.teaststorage.name
  storage_container_name = azurerm_storage_container.teastconfig.name
  type                   = "Block"
  source                 = "vars-pr-default-toggles.json"

  lifecycle {
    # 忽略源文件、内容哈希的变化,防止覆盖手动修改的Blob内容
    ignore_changes = [source, content_md5, content_sha256]
  }
}

核心逻辑说明

  1. Blob存在性检查:通过data "azurerm_storage_blob"查询目标Blob的状态,若Blob不存在,数据源的id字段会返回空值。
  2. 条件创建:利用count参数控制资源实例数,仅当Blob不存在时创建1个实例,存在则跳过创建。
  3. 保护现有内容:lifecycle.ignore_changes配置告诉Terraform忽略本地源文件的修改、Blob内容哈希的变化,确保即使本地文件更新或Blob被手动修改,Terraform也不会覆盖或替换现有Blob。

注意事项

  • 首次运行时,Blob不存在会自动创建并上传本地文件内容。
  • 后续运行Terraform时,只要Blob已存在,无论本地源文件是否变化、Blob内容是否被手动修改,都不会触发任何更新操作。
  • 若需强制更新Blob(谨慎操作,会覆盖现有内容),可执行terraform taint azurerm_storage_blob.teastfeaturetoggle[0],下次运行Terraform会重新创建该Blob。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:35:21