1

I'm currently learning for AZ-104 and trying to automate VM deployment with Powershell.

I want to create a VM with New-AzVMConfig and Set-AzVMOperatingSystem -Credential $cred, but with credentials I saved in AzureKeyVault.

The only solution I found was using a .NET script to convert the secret into cleartext.

$secret = Get-AzKeyVaultSecret -VaultName "somekeyvaultname" -Name "vmpassword"
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
   $secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
   [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
Write-Output $secretValueText

Is there a way to use the KeyVault object in a script so that it's used for the VM automatically? Or is this only possible with ARM templates?

itsamemarkus
  • 51
  • 1
  • 3

1 Answers1

2

You can get credentials from AzureKeyVault using AZ CLI or Powershell

AZ CLI Code example:

$Secret = az keyvault secret show --name "SecretName"--vault-name "KeyvaultName" | ConvertFrom-Json
$SecretValue= $Secret.value

Powershell Code example:

$Secret = Get-AzKeyVaultSecret -VaultName "KeyvaultName" -Name "SecretName"
$SecretValue = $secret.SecretValue | ConvertFrom-SecureString -AsPlainText
Andriy Bilous
  • 2,337
  • 1
  • 5
  • 16