首页 > 解决方案 > 如何将复杂的 DevOps 管道模板参数传递给脚本

问题描述

在 Azure DevOps 管道模板中,我将参数声明为数组/序列

parameters:
  mySubscription: ''
  myArray: []

steps:
- AzureCLI@2
  inputs:
    azureSubscription: ${{ parameters.mySubscription }}
    scriptType: pscore
    scriptPath: $(Build.SourcesDirectory)/script.ps1
    arguments: '-MyYAMLArgument ${{ parameters.myArray }}'

然后参数的值从管道定义传递为

steps:
- template: myTemplate.yml
  parameters:
    mySubscription: 'azure-connection'
    myArray:
    - field1: 'a'
      field2: 'b'
    - field1: 'aa'
      field2: 'bb'

我的问题是我无法在 YAML 语法(类型ToString())中按原样传递该数组,以便能够在我的模板中从 PowerShell 使用和处理该数组。尝试运行此管道时,出现以下错误: /myTemplate.yml (Line: X, Col: X): Unable to convert from Array to String. Value: Array. 错误消息中引用的行/列对应arguments: '-MyYAMLArgument ${{ parameters.myArray }}'于我的模板。

我还尝试将参数映射为我的脚本的环境

- AzureCLI@2
  inputs:
    azureSubscription: ${{ parameters.mySubscription }}
    scriptType: pscore
    scriptPath: $(Build.SourcesDirectory)/script.ps1
    arguments: '-MyYAMLArgument $Env:MY_ENV_VAR'
  env:
    MY_ENV_VAR: ${{ parameters.myArray }}

这也不起作用: /myTemplate.yml (Line: X, Col: Y): A sequence was not expected. 该时间线/列指的是MY_ENV_VAR: ${{ parameters.myArray }}.

有没有人遇到过类似的要求,将管道定义中定义的复杂类型(这里是对象的数组/序列)传递给 PowerShell 脚本?如果是这样,您是如何实现的?

标签: azure-devopsyamlazure-pipelinesazure-pipelines-yaml

解决方案


您现在可以使用 convertToJsonADO 管道中的函数将这些类型的参数转换为字符串:

parameters:
  - name: myParameter
    type: object
    default:
        name1: value1
        name2: value2

...

- task: Bash@3
  inputs:
    targetType: inline
    script: |
      echo "${{ convertToJson(parameters.myParameter) }}"

参考:https ://developercommunity.visualstudio.com/t/allow-type-casting-or-expression-function-from-yam/880210

convertToJson:https ://docs.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops#converttojson


推荐阅读