如何有条件地使用 Azure Pipelines 上的容器?

How can I conditionally use a container on Azure Pipelines?

我有一个带有矩阵的 AzP 作业,其中需要 运行 在容器中(旧编译器测试) 我怎样才能有条件地 运行 容器内的作业? 我尝试了下面的方法,但这似乎不起作用,即从未使用过容器,尽管我很确定我遵循了文档中的所有说明

stages:
  - stage: Test
    jobs:
      - job: 'Linux'
        strategy:
          matrix:
            GCC_10:
              CXX: g++-10
              VM_IMAGE: ubuntu-20.04
            GCC_9:
              CXX: g++-9
              VM_IMAGE: ubuntu-20.04
            Clang_3_7:
              CXX: clang++-3.7
              VM_IMAGE: ubuntu-20.04
              CONTAINER: ubuntu:16.04
        pool:
          vmImage: $(VM_IMAGE)
        ${{ if variables['CONTAINER'] }}:
          container:
            image: $[ variables['CONTAINER'] ]
            options:  "--name ci-container -v /usr/bin/docker:/tmp/docker:ro"

您不能使用 matrix 中的变量执行此操作,因为模板表达式 (${{ }}) 很早就呈现并且它们无法访问这些变量。请参阅此页面以了解如何处理管道:Pipeline run sequence

1. First, expand templates and evaluate template expressions.

...

4. For each job selected to run, expand multi-configs (strategy: matrix or strategy: parallel in YAML) into multiple runtime jobs.

但是您可以使用 runtime parameters 来获得所需的结果,模板表达式可用:

parameters:
  - name: matrix
    type: object
    default:
      GCC_10:
        CXX: g++-10
        VM_IMAGE: ubuntu-20.04
      GCC_9:
        CXX: g++-9
        VM_IMAGE: ubuntu-20.04
      Clang_3_7:
        CXX: clang++-3.7
        VM_IMAGE: ubuntu-20.04
        CONTAINER: ubuntu:16.04

stages:
  - stage: Test
    jobs:
      - ${{ each item in parameters.matrix }}:
          - job: Linux_${{ item.Key }}
            pool:
              vmImage: ${{ item.Value.VM_IMAGE }}
            ${{ if item.Value.CONTAINER }}:
              container:
                image: ${{ item.Value.CONTAINER }}
                options: --name ci-container -v /usr/bin/docker:/tmp/docker:ro
            steps:
              - bash: echo CXX = ${{ item.Value.CXX }}

这将呈现给

parameters:
- name: matrix
  type: object
  default:
    GCC_10:
      CXX: g++-10
      VM_IMAGE: ubuntu-20.04
    GCC_9:
      CXX: g++-9
      VM_IMAGE: ubuntu-20.04
    Clang_3_7:
      CXX: clang++-3.7
      VM_IMAGE: ubuntu-20.04
      CONTAINER: ubuntu:16.04
stages:
- stage: Test
  jobs:
  - job: Linux_GCC_10
    pool:
      vmImage: ubuntu-20.04
    steps:
    - task: Bash@3
      inputs:
        targetType: inline
        script: echo CXX = g++-10
  - job: Linux_GCC_9
    pool:
      vmImage: ubuntu-20.04
    steps:
    - task: Bash@3
      inputs:
        targetType: inline
        script: echo CXX = g++-9
  - job: Linux_Clang_3_7
    pool:
      vmImage: ubuntu-20.04
    container:
      image: ubuntu:16.04
      options: --name ci-container -v /usr/bin/docker:/tmp/docker:ro
    steps:
    - task: Bash@3
      inputs:
        targetType: inline
        script: echo CXX = clang++-3.7