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

如何在DevOps中实现符合企业规范的Azure ARM模板校验

ARM模板自定义校验规则实现方案

方案1:使用ARM TTK自定义校验规则(推荐)

ARM TTK是Azure官方的ARM模板规范校验工具,支持自定义测试规则,适配性更强。

  • 首先在执行校验的环境中安装ARM TTK,支持本地环境和DevOps构建节点直接安装使用。
  • 新建自定义测试用例文件Custom.SecurityRules.Tests.ps1,放入ARM TTK的testcases/deploymentTemplate目录下。
  • 测试用例内容如下:
# 校验httpsOnly规则
if ($Template.resources.properties | Where-Object { $_.PSObject.Properties.Name -eq 'httpsOnly' }) {
    $httpsOnlyValue = $Template.resources.properties.httpsOnly
    if ($httpsOnlyValue -ne $true) {
        Write-Error "配置了httpsOnly参数的资源必须设置为true,当前值为$httpsOnlyValue" -ErrorAction Stop
    }
}

# 校验minTlsVersion规则
if ($Template.resources.properties | Where-Object { $_.PSObject.Properties.Name -eq 'minTlsVersion' }) {
    $tlsValue = $Template.resources.properties.minTlsVersion
    if ($tlsValue -ne '1.2') {
        Write-Error "配置了minTlsVersion参数的资源必须设置为1.2,当前值为$tlsValue" -ErrorAction Stop
    }
}

# 校验ftpsState规则
if ($Template.resources.properties | Where-Object { $_.PSObject.Properties.Name -eq 'ftpsState' }) {
    $ftpsValue = $Template.resources.properties.ftpsState
    if ($ftpsValue -ne 'FtpsOnly') {
        Write-Error "配置了ftpsState参数的资源必须设置为FtpsOnly,当前值为$ftpsValue" -ErrorAction Stop
    }
}
  • 在DevOps流水线的构建阶段,部署ARM模板之前添加PowerShell步骤,运行校验命令:
    Test-AzTemplate -TemplatePath ./你的ARM模板路径.json -Test Custom.SecurityRules
    校验不通过时步骤会直接抛出错误,流水线自动终止。

方案2:流水线内置自定义脚本校验

不想引入额外工具的话,可以直接在流水线中添加自定义脚本解析校验,适配简单场景。

  • 在ARM模板部署步骤之前添加脚本执行步骤,支持PowerShell、Python等任意常用脚本语言。
  • 脚本逻辑为读取ARM模板JSON内容,遍历所有资源属性匹配三个规则,不符合就抛出错误终止流程。
  • Python示例代码如下:
import json

with open('你的ARM模板路径.json', 'r', encoding='utf-8') as f:
    template = json.load(f)

for resource in template.get('resources', []):
    props = resource.get('properties', {})
    res_name = resource.get('name', '未命名资源')
    # 校验httpsOnly
    if 'httpsOnly' in props and props['httpsOnly'] != True:
        raise Exception(f"资源{res_name}的httpsOnly值为{props['httpsOnly']},必须设置为true")
    # 校验minTlsVersion
    if 'minTlsVersion' in props and props['minTlsVersion'] != '1.2':
        raise Exception(f"资源{res_name}的minTlsVersion值为{props['minTlsVersion']},必须设置为1.2")
    # 校验ftpsState
    if 'ftpsState' in props and props['ftpsState'] != 'FtpsOnly':
        raise Exception(f"资源{res_name}的ftpsState值为{props['ftpsState']},必须设置为FtpsOnly")

补充说明

如果需要覆盖嵌套模板、参数文件中的对应参数校验,调整脚本的解析逻辑适配对应字段即可。后续新增其他校验规则也可以直接在现有测试用例或者脚本中扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:57:02