如何从Powershell中通过下载安全文件任务在构建管道上使用* .pfx证书

时间:2019-01-02 15:57:13

标签: azure azure-devops azure-powershell

我遇到了这个问题: 我需要从构建管道上使用的Powershell脚本连接到Azure订阅,但是出于安全性要求,我无法在代码上写入用户名和密码,因此我拥有带有凭据的pfx证书。 现在,我正在使用名为dowload安全文件的任务,将证书放入构建中。然后,我试图从Powershell代码访问证书。

我已经在机器上测试了代码,但是当我尝试在构建管道上使用它时,我无法以此方式访问证书

我遇到这样的错误

登录中... D:\ a \ 1 \ s \ Scripts \ fileName.ps1:脚本不起作用:无法识别术语“ cert.secureFilePath” 作为cmdlet,函数,脚本文件或可运行程序的名称。检查名称的拼写,或者路径是否为 包括在内,请验证路径正确无误,然后重试。

$tenantId  = "xxxxxxxxxxx"
$appId = "zzzzz"
$cert = %DOWNLOADSECUREFILE_SECUREFILEPATH% 
$certThumbprint = $cert.Thumbprint

Write-Host "Logging in...";

Login-AzureRmAccount `
-ServicePrincipal `
-TenantId $tenantId `
-ApplicationId $appId `
-CertificateThumbprint $certThumbprint

Tasks used on the build pipeline

1 个答案:

答案 0 :(得分:1)

下载的安全文件的完整路径存储在 $ env:DOWNLOADSECUREFILE_SECUREFILEPATH 环境变量中。有关“下载安全文件”任务的更多信息,请参阅此http://jsfiddle.net/notacouch/szwfgk4n/3/

我们可以使用以下代码获取certThumbprint

imageSeriesTemplate.urlTarget = "_blank";

如果我们不想直接在代码中使用用户名和密码。我们可以使用document。我们可以在代码中引用它。

  

如果要加密并安全存储该值,请选择该行末尾的“锁定”图标。添加完变量后,选择保存

Azure Pipeline library

  

您访问链接变量组中变量的值的方式与在管道本身中定义的变量完全相同。例如,要访问链接到管道的变量组中名为Customer的变量的值,请在任务参数或脚本中使用 $(customer)。但是,秘密变量(加密变量和密钥保险库变量)不能直接在脚本中访问-而是必须将它们作为自变量传递给任务

如果我在库中添加了名为 sSecStrPassword 的变量。然后可以将代码更改如下:

$CertificatePath = "$env:DOWNLOADSECUREFILE_SECUREFILEPATH"
$sSecStrPassword = "xxxxx"
$certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificateObject.Import($CertificatePath, $sSecStrPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
$thumbprint = $certificateObject.Thumbprint 

测试结果:

enter image description here

有关变量组的更多信息,请参阅此enter image description here。而Azure Key Vault是link的另一选择。

更新

以下是在Azure Devops管道中使用pfx文件的详细步骤。

  1. 准备一个.pfx文件。
  2. 添加下载安全文件任务并上传pfx文件。

security requirements

  1. 创建一个变量组并添加一个名为 sSecStrPassword
  2. 的变量

enter image description here

  1. 将变量链接到内部版本

enter image description here

  1. 添加powershell脚本任务,并在其中添加以下脚本。

enter image description here

function GetThumbprintPFX {
 param([string] $CertificatePath, [string]$Password)
 $certificateObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
 $certificateObject.Import($CertificatePath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet)
 $thumbprint = $certificateObject.Thumbprint
 return $thumbprint  
}


$thumbprint = GetThumbprintPFX -CertificatePath $env:DOWNLOADSECUREFILE_SECUREFILEPATH -Password '$(sSecStrPassword)'
Write-Host "$thumbprint"
  1. 排队构建并检查结果。

enter image description here

相关问题