首页 > 解决方案 > Azure 管道秘密变量不适用于 PR 触发器

问题描述

我有一个 azure 管道,其中包含一个在拉取请求上触发的秘密变量。触发时,秘密变量对管道不可用。

秘密变量在由提交到分支时触发。

管道

pr:
  branches:
    include:
    - '*'
trigger:
  branches:
    exclude:
    - '*'

jobs:
- job:
  pool:
    vmImage: 'ubuntu-latest'
  timeoutInMinutes: 360
  displayName: 'Running test'
  steps:
  - bash: |
      if [ -z "$(system.pullRequest.sourceRepositoryUri)" ]
      then
        python3 runTest.py \
          --config "blessedImageConfig-temp.json" \
          --code $(SecretCode)
      else
        python3 runTest.py \
          --config "blessedImageConfig-temp.json" \
          --pullRepo $(system.pullRequest.sourceRepositoryUri) \
          --pullId $(system.pullRequest.pullRequestNumber) \
          --code $(SecretCode)
      fi

通过 webUI 添加的秘密变量

输出和错误

Generating script.
========================== Starting Command Output ===========================
[command]/bin/bash --noprofile --norc /home/vsts/work/_temp/95f6ae7c-d2e1-4ebd-891c-2d998eb4b1d9.sh
/home/vsts/work/_temp/95f6ae7c-d2e1-4ebd-891c-2d998eb4b1d9.sh: line 7: SecretCode: command not found
usage: runTest.py [-h] [--config CONFIG] [--code CODE] [--pullId PULLID]
                  [--pullRepo PULLREPO]
runTest.py: error: argument --code: expected one argument
##[error]Bash exited with code '2'.

标签: azureazure-devopsazure-pipelines

解决方案


SecretCode:找不到命令

这个错误是由它是一个秘密变量引起的,它是在命令行中以不正确的方式传递的。

您可能对此感到困惑。但是,事实上,微软曾经用doc警告过这一点:永远不要在命令行上传递秘密。这是设计好的。

我曾经在我的 docker build 上遇到过类似的问题。我通过将秘密变量值映射到环境变量来解决它,这也在Variable的文档中提到。

对于您的Bash任务,还有关于秘密变量的解决方案:使用环境变量输入将秘密变量传递给此脚本'并设置 targetType == Inline is required

因此,您可以将以下脚本添加到您的Bash 任务脚本中,以将秘密变量映射到环境变量中:

inputs:
    targetType: 'inline'
    - script: 
      echo $code 
      env: 
        code: $(SecretCode)

推荐阅读