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

Terraform Azurerm:共享镜像版本Data块无法读取最新六位BuildId镜像

Azure Compute Gallery镜像版本读取异常问题

我在使用Azure Compute Gallery中基于Ubuntu的自定义镜像创建VM时,通过以下Terraform data块获取最新镜像版本以更新VM:

data "azurerm_shared_image_version" "stg_linux_image" {
  name                = "latest"
  image_name          = "my-ubuntu-image"
  gallery_name        = "my_custom_gallery"
  resource_group_name = "my_pe_rg"
}

此前该配置能正常读取最新版本,我通过$(Build.BuildId)生成镜像版本名称,例如1.0.99549、1.0.99690均能被正确识别。但当BuildId变为六位、生成版本名1.0.100150后,除非在data块中指定具体版本号1.0.100150,否则配置仍会读取旧版本1.0.99690,而非最新的六位BuildId版本。

问题原因

这是由于Azure Compute Gallery对latest标签的判定逻辑是按版本号的字符串字典序排序,而非数值大小排序。字符串比较时,"1.0.99690"会被判定为大于"1.0.100150"——因为从左到右比对字符时,"9"的ASCII码值大于"1",导致字典序中"99690"排在"100150"之前,latest标签因此指向了旧版本。

解决方法

  • 统一版本号格式:给BuildId补前导零,让所有版本的BuildId部分长度一致(比如固定为6位),例如将之前的99549改为099549。这样字符串字典序会和数值顺序匹配,latest标签就能正确识别最新版本。
  • 改用复数数据源手动排序:使用Terraform的azurerm_shared_image_versions(复数形式)数据源获取所有版本,再通过排序逻辑筛选最新版本。示例配置如下:
data "azurerm_shared_image_versions" "stg_linux_image" {
  image_name          = "my-ubuntu-image"
  gallery_name        = "my_custom_gallery"
  resource_group_name = "my_pe_rg"
}

locals {
  latest_image_version = sort(data.azurerm_shared_image_versions.stg_linux_image.names)[length(data.azurerm_shared_image_versions.stg_linux_image.names)-1]
}

# 后续使用local.latest_image_version作为目标版本号

注意:该方法需配合统一的版本号格式使用,否则sort的字典序排序仍可能不符合数值顺序。

  • 显式标记最新版本:在生成镜像版本的构建流程中,新增步骤调用Azure CLI将最新版本标记为latest:
az sig image-version update --resource-group my_pe_rg --gallery-name my_custom_gallery --gallery-image-definition my-ubuntu-image --gallery-image-version 1.0.100150 --set isLatest=true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:33:27