首页 > 解决方案 > 如何在变量模板中正确使用 Azure DevOps 函数?

问题描述

如何counter在变量模板中使用 Azure DevOps 函数?

到目前为止,我一直在使用该counter函数在管道中设置一个变量,并且该值已按预期设置 - 它从 1 开始,每次运行管道时都会递增。

变量模板 - /Variables/variables--code--build-and-deploy-function-app.yml

variables:
- name: major
  value: '1'
- name: minor
  value: '0'
- name: patch
  value: $[counter(format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']), 1)]
- name: branch
  ${{ if eq( variables['Build.SourceBranchName'], 'master' ) }}: 
    value: ''
  ${{ if ne( variables['Build.SourceBranchName'], 'master' ) }}: 
    value: -${{ variables['Build.SourceBranchName'] }}

但是,在将完全相同的变量移入变量模板之后, 的值counter是模板中指定的文字值。

深入研究模板的文档,我发现了一些关于模板表达式函数的词,以及如何使用函数的示例 -

您可以在模板中使用通用功能。您还可以使用一些模板表达式函数。

鉴于counter上面链接所指的页面上列出了这一点,我认为我可以使用它。但是,无论我尝试了什么,我都无法让它工作。这里有一些例子 -

${{ counter('${{ format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']) }}', 1) }}

${{ counter(format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']), 1) }}

$[counter('${{ format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']) }}', 1)]

我究竟做错了什么?


更新

我的变量模板如上所述,这是我在管道中使用它的方式 -

pr: none
trigger: none
    
variables:
- template: ../Variables/variables--code--build-and-deploy-function-app.yml

name: ${{ variables.major }}.${{ variables.minor }}.${{ variables.patch }}${{ variables.branch }}

运行后从日志中得到的扩展管道如下——

pr:
  enabled: false
trigger:
  enabled: false
variables:
- name: major
  value: 1
- name: minor
  value: 0
- name: patch
  value: $[counter(format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']), 1)]
- name: branch
  value: -CS-805
name: 1.0.$[counter(format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']), 1)]-CS-805

从扩展管道可以看出,patch变量没有被评估,导致name包含文字值 -

在此处输入图像描述

标签: functionvariablesazure-devops

解决方案


I inserted the same variables into the template and the patch variable works as expected. It seems that your counter is correct.

Here are my sample, you could refer to it:

Template Yaml: build.yml

variables:
- name: major
  value: '1'
- name: minor
  value: '0'
- name: patch
  value: $[counter(format('{0}.{1}-{2}', variables['major'], variables['minor'], variables['Build.SourceBranchName']), 1)]

Azure-Pipelines.yml

name: $(patch)

trigger:
- none

variables:
- template: build.yml  

pool:
  vmImage: 'windows-latest'

steps:
- script: echo $(patch)
  displayName: 'Run a one-line script'

In order to make the result more intuitive, I set patch variable to build name.

Here is the result:

enter image description here

Update:

Test with $(varname) and it could work as expected.

trigger:
- none

variables:
- template: build.yml  


name: $(major).$(minor)-$(patch)$(branch)

Result:

enter image description here

The $(varname) means runtime before a task executes.


推荐阅读