每次执行Terraform Plan时Azure CDN Front Door路由误报变更问题
问题描述
使用Terraform部署Azure CDN Front Door Profile时,每次执行terraform plan都会误判路由资源需要更新,实际配置并未修改。差异信息如下:
# azurerm_cdn_frontdoor_route.main-fe-resources will be updated in-place ~ resource "azurerm_cdn_frontdoor_route" "main-fe-resources" { ~ cdn_frontdoor_origin_group_id = "/subscriptions/e68adbb2-af8e-4b01-a7e8-2bf599d6d818/resourcegroups/ci-redacted-frontdoor/providers/Microsoft.Cdn/profiles/ci-redacted-frontdoor/origingroups/main-fe" -> "/subscriptions/e68adbb2-af8e-4b01-a7e8-2bf599d6d818/resourceGroups/ci-redacted-frontdoor/providers/Microsoft.Cdn/profiles/ci-redacted-frontdoor/originGroups/main-fe" id = "/subscriptions/e68adbb2-af8e-4b01-a7e8-2bf599d6d818/resourceGroups/ci-redacted-frontdoor/providers/Microsoft.Cdn/profiles/ci-redacted-frontdoor/afdEndpoints/ci-main/routes/main-fe-resources" name = "main-fe-resources" # (8 unchanged attributes hidden) # (2 unchanged blocks hidden) }
问题根源在于ID路径中resourceGroups/resourcegroups、originGroups/origingroups的大小写差异。尝试手动将脚本中的源组ID改为小写时,Terraform报错提示ID必须包含originGroups字符串。路由资源的创建代码如下:
resource "azurerm_cdn_frontdoor_route" "main-fe-resources" { name = "main-fe-resources" cdn_frontdoor_endpoint_id = azurerm_cdn_frontdoor_endpoint.main.id cdn_frontdoor_origin_group_id = azurerm_cdn_frontdoor_origin_group.main-fe.id cdn_frontdoor_origin_ids = [] cdn_frontdoor_rule_set_ids = [] enabled = true forwarding_protocol = "MatchRequest" https_redirect_enabled = true patterns_to_match = ["/assets-2022/*", "/_next/*"] supported_protocols = ["Http", "Https"] }
解决思路
- 升级AzureRM Provider版本:该问题大概率是旧版AzureRM Provider的大小写匹配bug,将provider版本升级至最新稳定版,新版本通常会修复这类ID大小写不一致导致的误判问题。
- 用Terraform字符串函数修正ID大小写:通过
replace函数强制将源组ID中的小写路径段替换为正确的大小写,既满足Terraform的验证要求,又与Azure实际返回的ID格式一致。修改后的代码如下:
resource "azurerm_cdn_frontdoor_route" "main-fe-resources" { name = "main-fe-resources" cdn_frontdoor_endpoint_id = azurerm_cdn_frontdoor_endpoint.main.id cdn_frontdoor_origin_group_id = replace( replace(azurerm_cdn_frontdoor_origin_group.main-fe.id, "/resourcegroups/", "/resourceGroups/"), "/origingroups/", "/originGroups/" ) cdn_frontdoor_origin_ids = [] cdn_frontdoor_rule_set_ids = [] enabled = true forwarding_protocol = "MatchRequest" https_redirect_enabled = true patterns_to_match = ["/assets-2022/*", "/_next/*"] supported_protocols = ["Http", "Https"] }
- 同步Terraform状态与实际资源:如果上述方法无效,可尝试使用
terraform import命令将现有路由资源导入Terraform状态,确保状态中的ID与Azure实际资源ID完全一致,消除差异判断。
内容的提问来源于stack exchange,提问作者Andy Holt
相关产品推荐
相关产品推荐

