【问题标题】:What do double curly braces '{{}}' mean in YAML files as used in Azure DevOps Yaml pipelines?Azure DevOps Yaml 管道中使用的 YAML 文件中的双花括号“{{}}”是什么意思?
【发布时间】:2021-12-31 19:24:50
【问题描述】:

最近正在研究 Azure DevOps 模板。并遇到了这种双花括号语法。只想知道如何在 Azure DevOps 中使用双花括号。

看过一些类似的帖子。

  1. Assign conditional value to variables in Azure DevOps

  2. Curly braces in Yaml files

  3. If else in Azure DevOps

  4. Conditional Variable Assignment in Azure DevOps

可以说,我在组中定义了一个变量,如下所示。

我们还可以在 yaml 文件中定义如下变量。

variables:
- name: BuildConfiguration
  value: 'Release'

- name: finalBuildArtifactName
  value: 'TempFolderName'

我们什么时候应该使用双花括号语法?

我知道并使用以下方法来引用变量。

  1. 变量['MyVar']
  2. variables.MyVar

与以上两个相比,我们可以用双花括号完成什么?

让事情在 yaml 管道中运行非常困难。进行更改,签入,运行管道,查看结果并再次返回。这非常耗时,至少可以说并不顺利。

【问题讨论】:

    标签: azure-devops azure-pipelines


    【解决方案1】:

    ${{}} 语法用于表达式。更重要的是还有另一个$[ <expression> ]。这就是区别:

    # Two examples of expressions used to define variables
    # The first one, a, is evaluated when the YAML file is compiled into a plan.
    # The second one, b, is evaluated at runtime.
    # Note the syntax ${{}} for compile time and $[] for runtime expressions.
    variables:
      a: ${{ <expression> }}
      b: $[ <expression> ]
    
    

    请查看文档here

    正如你在这里看到的

    steps:
    - task: PublishPipelineArtifact@1
      inputs:
        targetPath: '$(Pipeline.Workspace)'
        ${{ if eq(variables['Build.SourceBranchName'], 'main') }}:
          artifact: 'prod'
        ${{ else }}:
          artifact: 'dev'
        publishLocation: 'pipeline'
    

    您可以使用variables['Build.SourceBranchName'] 语法来访问变量。但是,

    variables:
      - name: foo
        value: fabrikam # triggers else condition
    
    pool:
      vmImage: 'ubuntu-latest'
    
    steps:
    - script: echo "start"
    - ${{ if eq(variables.foo, 'adaptum') }}:
      - script: echo "this is adaptum"
    - ${{ elseif eq(variables.foo, 'contoso') }}:
      - script: echo "this is contoso"
    - ${{ else }}:
      - script: echo "the value is not adaptum or contoso"
    

    您也可以使用variables.foo

    表达式通常用于条件评估、动态步骤/作业/阶段配置等。

    【讨论】:

    • 天啊,我根本不知道编译时间和运行时的概念!了解更多。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2020-05-23
    • 2018-03-20
    • 2012-03-30
    • 2013-03-10
    相关资源
    最近更新 更多