可以在Azure管道中完成条件变量分配吗?

时间:2019-08-16 23:27:06

标签: azure-devops yaml azure-pipelines

Azure管道具有ExpressionsConditions,但是我找不到基于条件将两个值之一分配给variable的方法。

有什么办法可以完成这个伪代码吗?

    ${{ if endsWith( variables['Build.SourceBranchName'], '/master' ) }}: 
      buildVersion: variables['mavenVersion']
    ${{ else }}: 
      buildVersion: variables['Build.SourceBranchName']

4 个答案:

答案 0 :(得分:9)

作为@Mike Murray答案的扩展,如果使用变量组,则必须将其他变量定义为名称/值对。在这种情况下,使用条件变量赋值如下:

{{1}}

答案 1 :(得分:6)

我比我想像的要近。这虽然不漂亮,但确实有效。 (具有更多yaml上下文)

variables:
  ${{ if eq( variables['Build.SourceBranchName'], 'master' ) }}: 
    buildVersion: ${{ variables['mavenVersion'] }}
  ${{ if ne( variables['Build.SourceBranchName'], 'master' ) }}: 
    buildVersion: ${{ variables['Build.SourceBranchName'] }}

  buildKey: ${{ format('{0}_{1}', variables['supportReleaseNumber'], variables['buildVersion']) }}
  buildNum: $[counter(variables['buildKey'], 1)]  # same as $(Rev:r), but more widely usable 

name: $(buildKey)_$(buildNum)  # build run name

答案 2 :(得分:2)

这应该可以解决问题。...

BuildVersion初始化为$(Build.SourceBranch) 如果是主分支,则将其更改为$(mavenVersion) 否则没有变化。

variables:
  mavenVersion: '1.0'
  buildVersion: $(Build.SourceBranch)

pool:
  vmImage: 'ubuntu-latest'

steps:

- script: echo '##vso[task.setvariable variable=buildVersion]$(mavenVersion)'
  displayName: "Set the buildVersion as mavenVersion if the Build.SourceBranch = 'refs/heads/master' "
  condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

- script: echo $(buildVersion)
  displayName: 'Printing the variable'

非主分支打印'refs / heads / branch_name',它是mavenVersion non-master branches prints 'refs/heads/branch_name' which is mavenVersion

master分支打印1.0,即mavenVersion master branch prints 1.0 which is mavenVersion

答案 3 :(得分:1)

@Mike Murray,谢谢您!我一直试图解决这个问题。 当从拉取请求触发构建时,SourceBranchName始终为“合并”。您的回答帮助我提出了此解决方案,以获取两种情况下的目标分支名称:手动构建和由pull-requests触发的构建:

${{ if ne( variables['Build.SourceBranchName'], 'merge' ) }}: 
    environment: ${{ variables['Build.SourceBranchName'] }}
  ${{ if endsWith( variables['System.PullRequest.TargetBranch'], 'dev' ) }}: 
    environment: dev
  ${{ if endsWith( variables['System.PullRequest.TargetBranch'], 'staging' ) }}: 
    environment: staging
  ${{ if endsWith( variables['System.PullRequest.TargetBranch'], 'master' ) }}: 
    environment: prod

不是很漂亮,但是终于可以了。

相关问题