使用 Azure 管道秘密变量在生成代理上设置环境变量

时间:2021-02-08 23:14:51

标签: azure-devops azure-pipelines

我们有一些依赖于某些秘密的功能测试。这些机密是从 Azure Key Vault (AKV) 获得的,为了从构建代理连接,我使用了环境变量和 AzureIdentity。我使用 powershell 在构建代理机器上设置了这些 env 变量。当我使用非秘密管道变量时,一切正常,但是当我切换到 AZURE_CLIENT_SECRET 的秘密管道变量时,身份验证开始失败。我尝试了使用脚本从秘密管道变量设置环境变量的方法,但它不起作用。我也尝试了 here 提到的方法,但这也不起作用。关于如何使用秘密管道变量设置环境变量的任何建议?

2 个答案:

答案 0 :(得分:0)

如果您明确地将秘密作为参数传递给脚本,那么脚本将可以访问它。 如果您想然后使用它来设置一个环境变量以在以后的脚本中使用,您可以使用不同的环境变量名称并让脚本发布您希望它在后续脚本中可用。这种方式违背了保密的目的,但如果那是你想要的。

答案 1 :(得分:0)

<块引用> <块引用>

关于如何使用秘密管道变量设置环境变量的任何建议?

如果您在下面的管道中设置了秘密变量。 enter image description here

然后使用脚本的环境或在 variables 块中映射变量以将机密传递到您的管道,如下面的脚本所示。请参阅:Set secret variables 了解详情。

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "Using the mapped env var for this task works and is recommended: $env:MY_MAPPED_ENV_VAR"
  env:
    MY_MAPPED_ENV_VAR: $(PAT) # the recommended way to map to an env variable

如果您使用 Azure Key Vault 变量,我们会在下面的 Azure Key Vault 中创建一个秘密变量 (PAT)。 enter image description here

所以我们可以在变量组中link secrets from an Azure key vault,如下。 enter image description here

现在我们可以在下面的脚本中使用这个变量组。请参阅:Reference secret variables in variable groups 了解详情。

variables: 
- group: 'AKVgroup' # variable group

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "Using the mapped env var for this task works and is recommended: $env:MY_MAPPED_ENV_VAR"
  env:
    MY_MAPPED_ENV_VAR: $(PAT) # the recommended way to map to an env variable

另一种方法是使用 Azure Key Vault task 像下面的脚本。请参阅:Use secrets from Azure Key Vault in Azure Pipelines 了解详情。

- task: AzureKeyVault@1
  inputs:
    azureSubscription: 'ARM'
    KeyVaultName: 'edwardkey'
    SecretsFilter: '*'
    RunAsPreJob: true

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "Using the mapped env var for this task works and is recommended: $env:MY_MAPPED_ENV_VAR"
  env:
    MY_MAPPED_ENV_VAR: $(PAT) # the recommended way to map to an env variable