如何在Azure DevOps Pipelines中遍历JSON文件并执行指定操作
Azure DevOps Pipeline遍历JSON操作列表解决方案
方案1:编译时遍历(推荐)
该方案性能最优,可直接使用Azure DevOps模板表达式的循环语法,前提是调整前端传参逻辑:
- 修改前端TypeScript传参代码,不要将actions数组序列化,直接传结构化数组,ADO的object类型参数可直接接收结构化对象:
const value = { actionType: "Create", stage: "test", region: "North", version: "v753", customer: "Hans" } interface Action { readonly action: string; readonly config: typeof value; } const actions: Array<Action> = []; for (let i = 0; i < 3; i++) actions.push({ action: `action(${i})`, config: value }) // 直接传结构化数组,不做JSON序列化 const body = { templateParameters: { actions: actions } }
- Pipeline配置保持object类型参数,直接用
each语法遍历即可,可直接读取对象内部字段:
name: Test-Deploy-$(Date:yyyyMMdd)-$(Date:hh-mm)$(Rev:.r) pool: vmImage: ubuntu-latest parameters: - name: actions type: object default: [] stages: - stage: test_stage displayName: Test stage jobs: - job: test displayName: Test the values steps: - ${{ each action in parameters.actions}}: - task: PowerShell@2 displayName: 执行${{ action.config.actionType }}操作(客户:${{ action.config.customer }}) inputs: targetType: 'inline' script: | Write-Host "操作标识:${{action.action}}" Write-Host "操作类型:${{action.config.actionType}}" Write-Host "部署环境:${{action.config.stage}}" Write-Host "部署区域:${{action.config.region}}" Write-Host "服务版本:${{action.config.version}}" Write-Host "所属客户:${{action.config.customer}}" # 此处添加调用AKS执行对应操作的逻辑
方案2:运行时遍历(兼容前端传序列化JSON的场景)
如果无法修改前端传参逻辑,只能接收序列化后的JSON字符串,就通过脚本在Pipeline运行阶段解析遍历:
name: Test-Deploy-$(Date:yyyyMMdd)-$(Date:hh-mm)$(Rev:.r) pool: vmImage: ubuntu-latest parameters: - name: actions type: string # 参数类型改为string接收JSON字符串 default: '' stages: - stage: test_stage displayName: Test stage jobs: - job: test displayName: Test the values steps: - task: PowerShell@2 displayName: 批量执行操作 inputs: targetType: 'inline' script: | # 解析传入的JSON字符串 $actionList = ConvertFrom-Json '${{ parameters.actions }}' # 遍历执行所有操作 foreach ($action in $actionList.actions) { Write-Host "操作标识:$($action.action)" Write-Host "操作类型:$($action.config.actionType)" Write-Host "部署环境:$($action.config.stage)" Write-Host "部署区域:$($action.config.region)" Write-Host "服务版本:$($action.config.version)" Write-Host "所属客户:$($action.config.customer)" # 此处添加调用AKS执行对应操作的逻辑 }
内容的提问来源于stack exchange,提问作者Anders Olesen
相关产品推荐
相关产品推荐

