Python: Get secrets from Azure Key vault with Azure CLI credentials

Christian Henrik Reich
2 min readOct 2, 2019

When working with Azure, I do find Python a great tool for writing small helper snippet scripts. E.g. Replay messages into EventHub from Cosmos DB, when developing streaming applications in Databricks. Often such scripts matures into something useful, and should be in version control, so others can use of them, or just as a backup.

One of the challenges with scripts accessing services, is that they often contains service keys, and scripts with keys, should not be checked into version control. When working with Azure, such an anti-pattern can be avoided, by using the Azure CLI and Azure Key vault.

The short story

First to rule out some confusing conecept, and I hope I can clarify without doing it more confusing. Azure Key vault, operates with keys and secrets. When accessing Azure Key vault for getting keys, a secret is accessed, not a key. So save you keys or other secrets in a Azure Key vault secret and not in a Azure Key vault key.

Instead of having keys in our scripts, we are calling Azure Key vault to gives us the keys when needed. The thing is, we have to authenticate us to Azure Key vault to be able to get the secrets from Azure Key vault.

By using the Azure CLI command AZ login, a users credentials are stored locally on the machine, and we don’t have to write things like logins, passwords or tokens in clear text for Azure Key vault in our scripts. These are taken from the stored credentials, never to been seen.

The long story

As a prerequisite, following should be installed, and somewhat little experince with them is assumed.

Log into Azure with Azure CLI, type in a shell

az login

A browser popups for logging in. Login and you credentials are stored on the machine.

If you have access to more than one Azure subscription, you must set the subscription the target Azure Key vault lives in, as default subscription.

az account set --subscription <SUBSCRIPTION_GUID>

We are using pip to install dependecies

pip install azure
pip install azure-cli-core

Last we get the latest version for a secret. A secret can have more versions, often it is the last one we want. Also, this is a generic example, feel free to wrap it in a function or alter it as it suits you.

The dns name of the Azure Key vault is needed, and the name of the secret.

There is another method, where all of the secrets from Azure Key vault instance are retrieved in one call. It saves a round trip om the network, but it requires more code to resolve the right secret.

--

--

Christian Henrik Reich
Christian Henrik Reich

Written by Christian Henrik Reich

Renaissance man @ twoday Kapacity, Renaissance man @ Mugato.com. Focusing on data architecture, ML/AI and backend dev, cloud and on-premise.

Responses (2)