为什么列表属性无法正确迭代?

问题描述 投票:0回答:1

提供字符串列表作为参数属性时,Azure Devops 无法迭代它。

有效

parameters:
- name: group
  type: object
  default:
  - 'myGroup'
- name: resourceNames
  type: object
  default:
  - 'name1'
  - 'name2'

jobs:
- job: TestJob

  steps:  
  - ${{ each n in coalesce(parameters.resourceNames, parameters.group) }}:
    - script: echo ${{ n }}

这会产生 2 个 cmdLine 任务,输出

name1
name2

不起作用

parameters:
- name: group
  type: object
  default:
  - 'myGroup'
- name: resources
  type: object
  default:
  - resourceNames:
    - 'name1'
    - 'name2'

jobs:
- job: TestJob

  steps:  
  - ${{ each r in parameters.resources }}:
    - ${{ each n in coalesce(r.resourceNames, parameters.group) }}:
      - script: echo ${{ n }}

这会导致验证错误:

/azure-pipelines.yml (Line: 19, Col: 17): Unable to convert from Object to String. Value: Object

有问题的地方是脚本,

echo ${{ n }}
。由于某种原因,Devops 认为
n
是一个对象,而实际上它应该是一个字符串。我怎样才能让它工作?

azure-devops azure-pipelines azure-pipelines-yaml
1个回答
0
投票

你可以用

n
表达式检查
convertToJson
的值,它实际上是一个对象。

- job: TestJob
  steps:  
  - ${{ each r in parameters.resources }}:    
    - ${{ each n in coalesce(r.resourceNames, parameters.group) }}:
      - script: echo ${MY_JSON3}
        env:
          MY_JSON3: ${{ convertToJson(n) }}   # check the n value.

enter image description here

要迭代列表,您应该

fix the list format in parameter
use correct each string

您可以参考下面的参数sample,需要去掉参数定义中

-
之前的破折号
resourceNames

enter image description here

并使用下面的表达式,转到资源名称级别来遍历列表:

  - ${{ each n in coalesce(parameters.resources.resourceNames, parameters.group) }}:
      - script: echo ${{ n }}

完成的固定yaml:

parameters:
- name: group
  type: object
  default:
  - 'myGroup'
- name: resources
  type: object
  default:
   resourceNames:               # remove dash - before resourceNames
    - 'name1'
    - 'name2'


jobs:
- job: TestJob
  steps:  
  - ${{ each n in coalesce(parameters.resources.resourceNames, parameters.group) }}:     # go to resourceNames level to literate through the list.
      - script: echo ${{ n }}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.