我在 azure-pipelines 中有一份工作,它接收可变数量的依赖项。 它可能有零个依赖项,或“n”个依赖项,具体取决于在此之前执行的先前作业。
让我们看一个例子:
文件:“dependent-job.yml”
parameters:
- name: Dependencies
type: Array
default:
- Job1
- Job2
Jobs:
- job: Variousdependencies
name: MyJob
${{ if parameters.Dependencies }}
dependsOn: ${{ parameters.Dependencies }}
condition: |
and(eq(dependencies.Job1.result, 'Succeeded'),
eq(dependencies.Job2.result, 'Succeeded'),
eq(variables[MyJobEnabled,'True'),
eq('${{ parameters.ForceJob }}','True')
)
如果我有 3 个依赖项,我需要在条件中添加另一个依赖项:
condition: |
and(eq(dependencies.Job1.result, 'Succeeded'),
eq(dependencies.Job2.result, 'Succeeded'),
eq(dependencies.Job3.result, 'Succeeded'),
eq(variables[MyJobEnabled,'True'),
eq('${{ parameters.ForceJob }}','True')
)
我想生成一些行来检查之前的作业是否使用each 语法成功结束。这是我尝试过的:
condition: |
and(${{ each job in dependencies }}
eq(dependencies.{{ job }}.result, 'Succeeded'),
eq(variables[MyJobEnabled,'True'),
eq('${{ parameters.ForceJob }}','True')
)
但是我在尝试运行它时收到以下错误:
The directive 'each' is not allowed in this context. Directives are not supported for expressions that are embedded within a string. Directives are only supported when the entire value is an expression.
Azure DevOps 编译时表达式不支持单个标量值中的嵌套表达式。
有一种方法可以实现你想要的:
为您的作业创建一个模板,该模板接受字符串(对象)数组形式的条件。在该模板中,您将字符串连接在一起以组装单个标量值。
# template - job with dynamic conditions
parameters:
- name: name
type: string
- name: displayName
type: string
default: ''
- name: dependsOn
type: object
default: []
- name: condition
type: object
default: []
- name: steps
type: stepList
jobs:
- job: ${{ parameters.name }}
displayName: ${{ coalesce( parameters.displayName, parameters.name ) }}
${{ if ne(length(parameters.condition), 0) }}:
condition: ${{ join( '', parameters.condition) }}
${{ if ne(length(parameters.dependsOn), 0) }}:
dependsOn: ${{ parameters.dependsOn }}
steps:
- ${{ parameters.steps }}
在调用模板中,动态构造条件语句数组。它看起来真的很奇怪,您需要包含
,
语句,因为它们通常出现在条件中。
# pipeline
parameters:
- name: dependencies
type: object
default:
- job1
- job2
- name: forceJob
type: boolean
default: false
jobs:
- job: job1
steps:
- script: echo 'job1'
- job: job2
steps:
- script: echo 'job2'
- template: job-with-dynamic-conditions.yml
parameters:
name: variousDependences
dependsOn: ${{ parameters.dependencies }}
condition:
- and(
- ${{ each job in parameters.dependencies }}:
- eq(dependencies.${{ job }}.result, 'Succeeded'),
- eq(variables['jobEnabled'], 'true'),
- eq( '${{ parameters.forceJob }}', 'true')
- )
steps:
- script: echo 'steps go here'