在 Azure DevOps Pipeline 模板中使用变量

Mic*_*ihs 5 yaml azure azure-devops azure-devops-pipelines

我们有一组 Azure DevOps 管道模板,我们可以在多个存储库中重复使用这些模板。因此,我们希望有一个包含所有模板变量的文件。

回购结构看起来像这样

template repo
  ??? template-1.yml
  ??? template-2.yml
  ??? variables.yml

project repo
  ??? ...
  ??? azure-pipelines.yml
Run Code Online (Sandbox Code Playgroud)

variables.yml这个样子的

...
variables:
  foo: bar
Run Code Online (Sandbox Code Playgroud)

template-1.yml我们导入这里variables.yml描述的

variables:
- template: variables.yml
Run Code Online (Sandbox Code Playgroud)

azure-pipelines.yml我们使用这样的模板

resources:
  repositories:
    - repository: build-scripts
      type: git
      name: project-name/build-scripts

steps:
  ...
  - template: template-1.yml@build-scripts
    
Run Code Online (Sandbox Code Playgroud)

当我们现在尝试运行管道时,我们收到以下错误消息:

template-1.yml@build-scripts (Line: 10, Col: 1): Unexpected value 'variables'
Run Code Online (Sandbox Code Playgroud)

Krz*_*tof 17

问题是因为您在步骤范围内使用了变量模板。而且variables根本不存在于那个级别。这应该适合你:

resources:
  repositories:
    - repository: build-scripts
      type: git
      name: project-name/build-scripts

variables:
  - template: template-1.yml@build-scripts

steps:
  ...
Run Code Online (Sandbox Code Playgroud)

这可以在任何可以使用变量的地方使用。例如,您可以这样使用它:

jobs:
- job: myJob
  timeoutInMinutes: 10
  variables:
  - template: template-1.yml  # Template reference
  pool:
    vmImage: 'ubuntu-16.04'
  steps:
  - script: echo My favorite vegetable is ${{ variables.favoriteVeggie }}.
Run Code Online (Sandbox Code Playgroud)


Jan*_*SFT 9

如果你的模板文件只有variables,你可以参考 Krzysztof Madej 的回答。

如果你的模板文件同时具有variables和 ,steps如下所示,它只能被extends使用。

# File: template-1.yml
variables: ...

steps: ...
Run Code Online (Sandbox Code Playgroud)

或者您可以将它们写在一个阶段中,如下所示。

# File: template-1.yml
stages:
- stage: {stage}
  variables: ...
  jobs:
  - job: {job}
    steps: ...
Run Code Online (Sandbox Code Playgroud)

然后将其作为单独的阶段插入。

# azure-pipelines.yml
stages:
- stage: ...
- template: template-1.yml
Run Code Online (Sandbox Code Playgroud)