Reputation: 647
I'm creating a VM using python and using custom script extension to download the certificate inside the VM and then saving it in Local Computer certificate trusted root certificate.
The only query I've is on the web there are very limited resource available for downloading the certificates from Azure Key Vault. Everyone suggest to login and then use the cmdlet to download which is not suitable when it comes to Custom Script Extension.
Below is the sample powershell cmdlet which ask to login and then download the certificate. But as we're running custom script extension we would not be able to authenticate.
$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)
Upvotes: 1
Views: 1527
Reputation: 42063
You could create an AD App in azure ad and use the service principal to login with non-interactively.
Follow the steps as below:
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 to your keyvault in the portal -> Access policies
-> Add new
-> Select principal
(just search for the name of your AD App, if you create an AD App, it will create a service principal in your tenant automatically) -> select the correct Secret/Key/Certificate permissions
(it depends on what operation you will do, in this case, you need to select Get
in Secret permissions
, also you can select all easily) -> click OK
-> Save
.
3.Then the service principal will have the permission to run Get-AzureKeyVaultSecret
, you just need to use it to login with 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
Upvotes: 2