Azure 管道参数作为秘密变量

Azure pipeline parameter as secret variable

我想将 PAT 作为管道参数传递给调用 Gitlab REST 的脚本 (gitlab.sh) API:

gitlab.sh

#!/bin/bash
set -e

MY_PAT="${MY_PAT}" #I want this to be secret and not printed in logs

function rest_api {
 curl -sSL -H "Content-Type: application/json" -H "PRIVATE-TOKEN:$MY_PAT" -X POST
   --data '{"name": "my-group","path": "my-group"}'
   https://gitlab.example.com/api/v4/groups 
}

rest_api

azure-pipelines.yml

    pool:
      vmImage: 'ubuntu-latest'
    parameters:
     - name: myPAT
      displayName: 'My PAT'
      type: string  
    
    steps:
    - checkout: self
    - script: |  
        echo "Creating group in Gitlab"
        export MY_PAT=${{parameters.myPAT}} #how can I pass this secretly to gitlab.sh
        bash -x gitlab.sh
      condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/feature'))
      displayName: 'Creating group in Gitlab'  

如果你想设置一个秘密,你应该使用如下的日志命令

- bash: |
    echo "##vso[task.setvariable variable=MY_PAT;issecret=true]${{parameters.myPAT}}"
  name: SetSecret

在下一个任务中,您应该可以使用 MY_PAT 个秘密变量。但是,由于您将它作为运行时参数传递,因此它可以打印在日志中。

例如

parameters:
- name: myPAT
  displayName: 'My PAT'
  type: string

trigger: none
pr: none

pool:
  vmImage: 'ubuntu-latest'


steps:
- bash: |
    echo "You can use macro replacement to get secrets, and they'll be masked in the log: ${{parameters.myPAT}}"

- bash: |
    echo "##vso[task.setvariable variable=MY_PAT;issecret=true]${{parameters.myPAT}}"
  name: SetSecret

- bash: |
    echo "You can use macro replacement to get secrets, and they'll be masked in the log: $(MY_PAT)"

对于第一次打印,我得到了:

You can use macro replacement to get secrets, and they'll be masked in the log: MySecret

第二个:

You can use macro replacement to get secrets, and they'll be masked in the log: ***

所以通过参数传递秘密你可能会暴露它。请注意这一点。

我创建了一个功能请求来支持作为秘密的运行时参数 here。如果您认为这是有价值的功能,请随时投票。

pool:
  vmImage: 'ubuntu-latest'
parameters:
 - name: myPAT
  displayName: 'My PAT'
  type: string  

steps:
- checkout: self
- bash: |
    echo "##vso[task.setvariable variable=MY_PAT;issecret=true]${{parameters.myPAT}}"
  name: SetSecret

- script: |  
    echo "Creating group in Gitlab"
    bash -x gitlab.sh
  condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/feature'))
  displayName: 'Creating group in Gitlab'
  env:
    MY_MAPPED_ENV_VAR: $(MY_PAT) # the recommended way to map to an env variable

然后你可以在你的 sh 文件中使用 MY_MAPPED_ENV_VAR 作为 enviromnet variable