使用自定义脚本扩展从 Azure Key Vault 下载证书

Downloading Certificate from Azure Key Vault using Custom script extension

我正在使用 python 创建 VM,并使用自定义脚本扩展在 VM 中下载证书,然后将其保存在本地计算机证书受信任的根证书中。

我唯一的查询是在网络上,可用于从 Azure Key Vault 下载证书的资源非常有限。大家建议先登录再用cmdlet下载,自定义脚本扩展不太适合

下面是要求登录然后下载证书的示例 powershell cmdlet。但由于我们是 运行 自定义脚本扩展,我们将无法进行身份验证。

$vaultName = "YOUR-KEYVAULT-NAME"
$certificateName = "YOUR-CERTIFICATE-NAME"
$pfxPath = [Environment]::GetFolderPath("Desktop") + "$certificateName.pfx"
$password = "YOUR-CERTIFICATE-PASSWORD"
$pfxSecret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName
$pfxUnprotectedBytes = [Convert]::FromBase64String($pfxSecret.SecretValueText)
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($pfxUnprotectedBytes, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$pfxProtectedBytes = $pfx.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $password)
[IO.File]::WriteAllBytes($pfxPath, $pfxProtectedBytes)

您可以在 azure ad 中创建一个 AD 应用程序并使用服务主体通过 non-interactively 登录。

按照以下步骤操作:

1.Create an Azure Active Directory application and create a secret for the app, save the secret by yourself and get values for signing in.

2.Navigate 到您在门户中的密钥库 -> Access policies -> Add new -> Select principal(只需搜索您的 AD 应用程序的名称,如果您创建一个 AD 应用程序,它会自动在您的租户中创建一个服务主体)-> select 正确的 Secret/Key/Certificate permissions(这取决于您要执行的操作,在这种情况下,您需要 select Get in Secret permissions, 也可以 select 都轻松) -> 点击 OK -> Save.

3.Then服务主体将拥有运行Get-AzureKeyVaultSecret的权限,你只需要用non-interactively.

登录即可
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "your AD App secret" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal 

Get-AzureKeyVaultSecret -VaultName $vaultName -Name $certificateName