Azure 管道:如何在条件中使用输出变量

时间:2021-06-17 16:58:28

标签: powershell azure-pipelines azure-pipelines-yaml

我正在研究在 Windows 自托管代理上运行的管道。 我需要调用一个脚本,在一个阶段初始化一个变量,并在下一阶段的条件下使用该变量。

这是我的 Yaml:

stages:
  - stage: Init
    jobs:
    - job: RunScript
      steps:
        - task: PowerShell@2
          name: compareFiles
          inputs:
            targetType: filePath
            filePath: '***\compareFileContent.ps1'

  - stage: DisplayStage
    dependsOn: Init
    variables:
      areFilesDifferent: $[ stageDependencies.Init.RunScript.outputs['compareFiles.areDifferent'] ]
    jobs:
    - job: Display
      steps:
        - script: |
            echo $(areFilesDifferent)

  - stage: DeploymentStage
    dependsOn: DisplayStage
    variables:
      areFilesDifferent: $[ stageDependencies.Init.RunScript.outputs['compareFiles.areDifferent'] ]
    condition: eq( '$(areFilesDifferent)', 'true' )
    jobs:
    - deployment: DeploymentJob
      environment: 'ATest'
      strategy:
        runOnce:
          deploy:
            steps:
              - checkout: none
              - task: CmdLine@2
                inputs:
                  script: |
                    echo EnvName Finally: $(areFilesDifferent)

这是我的 Powershell: '***\compareFileContent.ps1'

$equal = $filetext1 -ceq $filetext2 # case sensitive comparison
$equalString = (&{If($equal) {"true"} Else {"false"}})
echo "##vso[task.setvariable variable=areDifferent;isOutput=true]$equalString"

显示作业打印“true”,但阶段条件始终返回 false。 我尝试使用返回布尔值而不是字符串的函数,但没有用。 我在条件中尝试了不同的语法,总是返回 false。 我尝试将条件下移到第一个作业,但在这种情况下,在评估条件之前会触发环境批准。

我的目标是 Powershell 决定是否应该使用该环境。 使用环境时,有一个审批步骤。

我确实为此写了另一篇文章 (Azure pipelines, question about variables, powershell and deployments),现在我成功地从脚本中检索了 Output 变量,但我仍然无法在某个条件下使用它。

你能帮我吗?

1 个答案:

答案 0 :(得分:0)

你应该试试这个:

  - stage: DeploymentStage
    dependsOn: DisplayStage
    variables:
      areFilesDifferent: $[ stageDependencies.Init.RunScript.outputs['compareFiles.areDifferent'] ]
    condition: eq(dependencies.Init.outputs['RunScript.compareFiles.areDifferent'], 'true')
    jobs:
    - deployment: DeploymentJob
      environment: 'ATest'
      strategy:
        runOnce:
          deploy:
            steps:
              - checkout: none
              - task: CmdLine@2
                inputs:
                  script: |
                    echo EnvName Finally: $(areFilesDifferent)

这里的问题是 stageDependency 在阶段级别的语法不正确。您应该使用依赖表达式,然后也通过作业名称引用变量。请检查文档 here