如何使用 Power Shell 脚本从 Key Vault 获取证书?

时间:2021-05-15 10:34:15

标签: azure powershell azure-devops

我需要有关此场景的帮助。我们在 azure 密钥保管库中有一个证书,需要将其下载到 Windows VM,以便我们的 .net 应用程序在 iis 上运行。我可以毫无问题地将证书上传到 Azure 密钥库。我正在运行一个 azure devops powershell 任务内联 powershell 脚本。

  1. 它将使用具有适当登录凭据的 conenct-azaccount 连接到 azure。enter code here
  2. 我们运行 invoke-azvmssrunco​​mmand 并指定需要作为参数传递的脚本路径和变量。
  3. 在 PowerShell 脚本中,我们有脚本可以在连接到 azure vm 后从 azure keyvualt 获取证书

下面是错误 错误:发送请求时发生错误。需要你的想法。 Invoke-AzVmssVMRunCommand -VMScaleSetName dev-CTUS -ResourceGroupName RG -InstanceId $instanceid -CommandId 'RunPowerShellScript'-ScriptPath "path"\downloadcertfromkeyvault.ps1" -Parameter @{"vaultname"="keyvault name";"certname"="app- DEV";"password"="jdksjkdjalksd";"said"="";"sapuserid"; password"="password";"devSubscriptionId"="ZXXXXXXXXXX"} -Debug

这是我在 azure devops powershell 内联脚本中使用的命令。

inside powershell script 

$SecurePassword = "$sapassword" | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $said, $SecurePassword
Connect-AzAccount -Credential $Credential -Tenant "XXXXXXXXXXXX-a68c-41e5-XXXXXXXX"

Write-log "setting subscription to retrive certs"
Set-AzContext $devSubscriptionId

$password = "$password"

$password = ConvertTo-SecureString -String "$password" -AsPlainText -Force

$cert = Get-AzKeyVaultCertificate -VaultName $vaultname -Name $certname
$secret = Get-AzKeyVaultSecret -VaultName $vaultname -Name $cert.Name 
$pfxpath = [System.Environment]::GetFolderPath("Desktop")
$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($secretByte, "", "Exportable,PersistKeySet")
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$pfxFileByte = $x509Cert.Export($type, $password)

# Write to a file
[System.IO.File]::WriteAllBytes("$pfxpath\$certname.pfx", $pfxFileByte)

$certificate= Get-ChildItem -path cert:\LocalMachine\My`   `

Write-Log $certificate

0 个答案:

没有答案