首页 > 解决方案 > 使用 Azure 管道秘密变量在构建代理上设置环境变量

问题描述

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

标签: azure-devopsazure-pipelines

解决方案


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

如果您在下面的管道中设置秘密变量。 在此处输入图像描述

然后使用脚本的环境或在变量块中映射变量以将秘密传递到您的管道,如下面的脚本。有关详细信息,请参阅:设置秘密变量

- 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 )。 在此处输入图像描述

因此,我们可以在变量组中 链接来自 Azure 密钥保管库的机密,如下所示。在此处输入图像描述

现在我们可以在下面的脚本中使用这个变量组。有关详细信息,请参阅:参考变量组中的秘密变量。

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 任务,如下面的脚本。有关详细信息,请参阅:在 Azure Pipelines 中使用 Azure Key Vault 中的机密

- 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

推荐阅读