TIP

🔥 Make sure you star the repo to keep up to date with new tips and tricks.

💡 Learn more : Microsoft Azure Key Vault.

📺 Watch the video : Getting started with Azure Key Vault.

Using secrets in scripts

When you write deployment scripting you often need secrets / passwords. Using these secrets is often done by using variables and storing the plain text password or secure object (which is still security through obscurity). In some cases people paramatarize the values and have to input the secrets / passwords upon runtime. If you're working with a large number of secrets the latter can be quite time consuming.

1. Leveraging the Azure Key Vault

When using Microsoft Azure, it's a best practice to store your secrets in the Azure Key Vault. This can also be done when scripting your deployments. If you're deploying ARM Templates, you can query the key vault directly during the deployment (https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/key-vault-parameter?tabs=azure-cli) and this is often the most secure way.

However, sometimes you're just not deploying using ARM templates or you're using a combination of tools. Maybe you're not even deploying to Azure and you just need a place to store your secrets. Key Vault is there for you 😃

2. Code samples

Note that the code requires you t be logged in to Azure using either Azure PowerShell or Azure CLI (depending on your preference).

The following code will retrieve all the secrets from your Azure KeyVault and store them in the hash table "$keys".

Upon succesful execution you can request the secrets from the table by simple parsing "$keys.NameOfYourKeyVaultSecret"

For example "$keys.storageAccountkey" would return the secret value of the "storageAccountKey" as stored in the Azure KeyVault.

$keyvaultName = 'KeyVaultName'
$secrets = Get-AzKeyVaultSecret -VaultName $keyvaultName

$keys =@{}
foreach ($secret in $secrets)
    {
        $secretName = $secret.name
        
        $key = (Get-AzKeyVaultSecret -VaultName $keyvaultName -name $secretName).SecretValueText
        $keys.Add("$secretName", "$key")
    }

1
2
3
4
5
6
7
8
9
10
11
12
Azure CLI version
$keyvaultName = 'KeyVaultName'
$secrets = az keyvault secret list --vault-name $keyvaultName |convertFrom-Json
    
$keys =@{}
foreach ($secret in $secrets)
    {
        $secretName = $secret.name

        $key = az keyvault secret show --vault-name $keyvaultName --name $secretName --query value
        $keys.Add("$secretName", "$key")
    }
1
2
3
4
5
6
7
8
9
10
11